Re: Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

2006-07-02 Thread Paddy

[EMAIL PROTECTED] wrote:
> This has been bothering me for a while. Just want to find out if it
> just me or perhaps others have thought of this too: Why shouldn't the
> keyset of a dictionary be represented as a set instead of a list?

I think the order of the items returned by keys() and values() are
related. I decided on a short  empirical test:

>>> import random
>>> n=50
>>> d = dict((i,random.randint(0,n-1)) for i in range(n))
>>> k,v = d.keys(), d.values()
>>> [d[k[i]] == v[i]  for i in range(n)]
[True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True]
>>> ## for larger n try
>>> # False in [d[k[i]] == v[i]  for i in range(n)]

The order of keys() and the order of values() are related, so a change
to returning sets would also loose this functionality.

Mind you, Never rely on that implied ordering. Always use items().

And so *if* sets were returned for keys() and values() then it should
for items() too.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beautifulsoup .vs tidy

2006-07-02 Thread Fredrik Lundh
Ravi Teja wrote:

>> Of course, lxml should be able to do this kind of thing as well. I'd be
>> interested to know why this "is not a good idea", though.
> 
> No reason that you don't know already.
> 
> http://www.boddie.org.uk/python/HTML.html
> 
> "If the document text is well-formed XML, we could omit the html
> parameter or set it to have a false value."
> 
> XML parsers are not required to be forgiving to be regarded compliant.
> And much HTML out there is not well formed.

so?  once you run it through an HTML-aware parser, the *resulting* 
structure is well formed.

a site generator->converter->xpath approach is no less reliable than any 
other HTML-scraping approach.



-- 
http://mail.python.org/mailman/listinfo/python-list


Request for addition to Preferences

2006-07-02 Thread JohnJohnUSA
I wasn't sure how to get my request to the appropriate person so I am
posting it here!

When I log in to this site, I normally want to go to the Python forum.
 I can get there via a series of mouse clicks.  I would prefer to have
the option of specifying in my Preferences where I want to be
positioned within this site upon login.  After setting
"python" in my Preferences, I would automatically be
positioned on the python forum page.  This would save me and others a
lot of work in getting to where I want to be.

The dropdown list that I saw somewhere on this site could be placed in
the Preferences section to enable me to select where I want to go upon
log in and I would be positioned there automatically.

Can this feature be implemented.  I would think that everyone coming
to this site may like it as it would be a good time and work saver. 
One would also have the option of not selecting a specific location
in which case they would be positioned on the main page as everyone
currently is.

Thanks in advance for considering adding this feature to this website!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behavior with staticmethods

2006-07-02 Thread [EMAIL PROTECTED]
THANK YOU!

Now I can actually worry about the advantages/disadvantages!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for addition to Preferences

2006-07-02 Thread Fredrik Lundh
JohnJohnUSA wrote:

> I wasn't sure how to get my request to the appropriate person so I am
> posting it here!

> When I log in to this site

what site ?

> I normally want to go to the Python forum.

what forum ?  this is the comp.lang.python newsgroup, which is also 
available as a mailing list hosted by python.org:

 http://www.python.org/community/lists/

if the terms "mailing list" and "newsgroup" are new to you, please see:

 http://en.wikipedia.org/wiki/Electronic_mailing_list
 http://en.wikipedia.org/wiki/Newsgroup



-- 
http://mail.python.org/mailman/listinfo/python-list


re:Request for addition to Preferences

2006-07-02 Thread JohnJohnUSA
The site that I am referring to is the one that I used to post my
request located at:

http://www.nixforum.org/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for addition to Preferences

2006-07-02 Thread Fredrik Lundh
JohnJohnUSA wrote:

> The site that I am referring to is the one that I used to post my
> request located at:
> 
> http://www.nixforum.org/

who cares ?  they're not hosting this newsgroup; they're just stealing 
the content, making it look like it's their "programming python" forum 
so they can plaster google ads all over it; if you have trouble with 
their site, complain to them, or find a better way to read this group.

it's not like anyone's forcing you to use a crap site run by people with 
no ethics, you know.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a limited set of instanceses of a class

2006-07-02 Thread madpython
Thanks Alex and Scott for your lead. It would've taken me forever
trying to figure it out by myself :)

I am affraid I didn't specify initially one thing and that led to a
confusion: there is no need to pick an instance from the weakref
dictionary, just return None if there are already 5 instances. But on
the other hand if a hardref to an object was deleted, it's place can be
taken by another one.
Here's what i mean (and where the problem is):

#build a list of 5 elements
instList=[]
for i in range(7):
ainst=A()
if ainst:
instList.append(ainst)

for i in range(5):
instList.remove(instList[0]) #here the hardref is deleted
ainst=A()
while not ainst:
#make shure that ainst is not NoneType
gc.collect()
time.sleep(1)   #wait 1 sec for gc() to clean the memory
ainst=A()   #try again
instList.append(ainst) #new object added

the priblem is that ~3 out of 10 times the test part run into infinite
loop because of unsatisfied condition (while not ainst:) - memory
cannot be freed therefore new instance of A isn't permitted.


#!/usr/bin/env python
import weakref,random
import types,gc
import time
class Limited5(object):
__weakrefdict=weakref.WeakValueDictionary()
def __new__(cls,*args,**kwargs):
if len(cls.__weakrefdict)<5:
instance=super(Limited5,cls).__new__(cls,*args,**kwargs)
cls.__weakrefdict[id(instance)]=instance
return instance
#return random.choice(cls.__weakrefdict.values())
return None #no need to pick an instance
class A(Limited5):
counter=0
def __init__(self):
self.instCounter=self.counter
A.counter+=1
def getId(self):
return id(self)

if __name__=="__main__":
instList=[]
# populate the initial list of objects
#make shure that there are only 5 elements
for item in range(7):
ainst=A()
if hasattr(ainst,"getId"):
print ainst.getId()," -- ",ainst.instCounter
instList.append(ainst)
print "-"

#delete and recreate an arbitrary element in the instList
for i in range(len(instList)):
instList.remove(instList[random.choice(range(len(instList)))])
ainst=A()
while not ainst:#here is an unstable part
ainst=A()   #sometimes the loop becomes infinite
print gc.collect()  #decpite the explicit call for gc() to
start
time.sleep(1)
print "*",
instList.append(ainst)
for item in instList:
print item.getId()," -- ",item.instCounter
#print "---> ",item
print ""

-- 
http://mail.python.org/mailman/listinfo/python-list


Python CGI Scripting Documentation

2006-07-02 Thread Vlad Dogaru
Hello,

I would like to learn web scripting with Python (sure, everyone uses
PHP, but I don't like the syntax and Python is more general-purpose
and... well, I guess you people know the advantages better than me).
Where can I get a thorough introduction to both CGI and using Python
for CGI? That includes installing my own web server (at home, for
testing) and starting from scratch (by that I mean I have near null
experience with CGI).

I have tried looking through the source code of MoinMoin, but it's just
too advanced for me -- I simply don't know where to start. Right now,
I'll take any and all suggestions. However, please suggest books or
articles that are up-to-date on Python programming; I'd hate to see
that I'm studying obsolete texts or the like.

Thanks in advance,
Vlad

--
If I make any mistake, be it regarding English or Usenet, do point it
out to me. Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Python CGI Scripting Documentation

2006-07-02 Thread Vlad Dogaru
Hello,

I would like to learn web scripting with Python (sure, everyone uses
PHP, but I don't like the syntax and Python is more general-purpose
and... well, I guess you people know the advantages better than me).
Where can I get a thorough introduction to both CGI and using Python
for CGI? That includes installing my own web server (at home, for
testing) and starting from scratch (by that I mean I have near null
experience with CGI).

I have tried looking through the source code of MoinMoin, but it's just
too advanced for me -- I simply don't know where to start. Right now,
I'll take any and all suggestions. However, please suggest books or
articles that are up-to-date on Python programming; I'd hate to see
that I'm studying obsolete texts or the like.

Thanks in advance,
Vlad

--
If I make any mistake, be it regarding English or Usenet, do point it
out to me. Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python CGI Scripting Documentation

2006-07-02 Thread placid

Vlad Dogaru wrote:
> Hello,
>
> I would like to learn web scripting with Python (sure, everyone uses
> PHP, but I don't like the syntax and Python is more general-purpose
> and... well, I guess you people know the advantages better than me).
> Where can I get a thorough introduction to both CGI and using Python
> for CGI? That includes installing my own web server (at home, for
> testing) and starting from scratch (by that I mean I have near null
> experience with CGI).
>
> I have tried looking through the source code of MoinMoin, but it's just
> too advanced for me -- I simply don't know where to start. Right now,
> I'll take any and all suggestions. However, please suggest books or
> articles that are up-to-date on Python programming; I'd hate to see
> that I'm studying obsolete texts or the like.

Chapter 12 of Programming Python 2nd Edition by Mark Lutz

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

2006-07-02 Thread bearophileHUGS
Paddy:
> Mind you, Never rely on that implied ordering. Always use items().

Using dict.items() is probably better, but the manual says:

>If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are 
>called with no intervening modifications to the dictionary, the lists will 
>directly correspond. This allows the creation of (value, key) pairs using 
>zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for 
>the iterkeys() and itervalues() methods:<

Is this going to change?


dict.keyset() seems nice, but you usually don't want to make a too much
big API.
Keeping APIs small is very important in Python, otherwise you need the
manual to write code.
I think a better solution to solve such key set problems is to optimize
Python itself, so Python computes set(dict) really fast (it can just
"copies" the hash of the dict).

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
valpa <[EMAIL PROTECTED]> wrote:
>I'm a net admin for about 20 unix servers, and I need to frequently
>telnet on to them and configure them.
>It is a tiring job to open a xterm and telnet, username, password to
>each server.

Don't use telnet. it's clumsy and has security issues.

Use ssh with RSA or DSA keys. Then you simply do:

ssh [EMAIL PROTECTED]

in an xterm and you are loggedis as user username on server
machinename. It's vastly more secure and more reliable. 

If you're talking about initial setup of a machine (OS installation or
whatever), our solution was to have a post-install CD or floppy which
fetched standard server configuration data. This included an ssh
public key for our ssh-key distribution, so after running the
post-install disc, we could push out staff ssh-keys and logins were
available.




-- 
Jim Segrave   ([EMAIL PROTECTED])

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python CGI Scripting Documentation

2006-07-02 Thread Michael
Sybren Stuvel wrote:

> Why use CGI when you can use a framework that's so much easier and
> more powerful?

Lots of possible answers, a few:
   * Fun
   * Transferable skills
   * No single solution is ever the answer to all problems
 (not all problems are nails, not all solutions are hammers)
   * Someone needs to understand the nuts and bolts of what's going on
   * Just because something is difficult doesn't mean its not worth doing
   * Understanding what's actually going on

But the killer answer for me really is: "Why not" :-)

Have fun :-)


Michael.

-- 
http://mail.python.org/mailman/listinfo/python-list


PyPy and constraints

2006-07-02 Thread Paddy
I followed the recent anouncement of version 0.9 of PyPi and found out
that there was work included on adding constraint satisfaction solvers
to PyPy:
  http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html

I was wondering if this was a possibiity for "mainstream" python, and
wether the the algorithms used could handle the kind of use mentioned
here:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/d297170cfbf1bb34/d4773320e3417d9c?q=constraints+paddy3118&rnum=3#d4773320e3417d9c

Thanks, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP thought experiment: Unix style exec for function/method calls

2006-07-02 Thread Michael
Carl Banks wrote:

> Maybe look to see how tail-recursive optimization in languages such as
> Scheme work, and whether it can be generalized.

Thanks for the feedback - I should've remembered tail recursion.

> I doubt this would be possible without a major change in how functions
> work in Python.  The most obvious problem is that functions refer to
> local variables by an index, not by name.  If you were to execute the
> bytecode of one function in the stack frame of another, Bad Things
> would happen.

Oh that's a pity. I can see why you'd do that, but it is a pity. That would
tend to imply that _replacing_ rather than _reusing_ the top frame is the
most doable/likely/sensible approach. (It's also very obviously easier to
emulate)

(And yes, I was consider reusing or replacing *only* the top stack frame.
Replacing seems better with retrospect, even if reusing seemed like a fun
idea :-)

> > def set_name():
> > name = raw_input("Enter your name! > ")
> > cexe greet()
> >
> > def greet():
> > print "hello", name
> >
> > cexe set_name()
> > print "We don't reach here"
> > --
> >
> > This would execute, ask for the user's name, say hello to them and then
> > exit - not reaching the final print "We don't reach here" statement.
> 
> Only if you were to replace the whole stack.  If you only replace or
> reuse the top frame, I would think greet would exit and execution would
> resume right after the point from which set_name was called.  Or am I
> misunderstanding what you want?

I think you are. 

In the hypothetical example, your code by definition gets called by
something. This leave a hypothetical return point. For the moment, lets
make things clearer by what I mean by changing the example to this:

> > 1 def set_name():
> > 2 name = raw_input("Enter your name! > ")
> > 3 cexe greet()
> > 4
> > 5 def greet():
> > 6 print "hello", name
> > 7
> > 8 def main():
> > 9 cexe set_name()
> > 10print "We don't reach here"
> > 11
> > 12main()
> > 13print "see what I mean?"
> > --

at line 12, we call 8. We can argue then our stack looks like this:
[ { "context" : "main", pc : 8 }, { "context" : "__main__", pc : 12 }, ]

(I'm going to push/pop at the front of the list)

We reach line 9, before we execute the code there:
[ { "context" : "main", pc : 9 }, { "context" : "__main__", pc : 12 }, ]

After we execute, it does a cexe call of set_name, not a normal call of
set_name. This causes the top stack frame to be _replaced_ :

[ { "context" : "set_name", pc : 1 }, { "context" : "__main__", pc : 12 }, ]

We then carry on, until we reach line 3, at which point before execution our
stack would look something like:

[ { "context" : "set_name", pc : 3 }, { "context" : "__main__", pc : 12 }, ]

And after:

[ { "context" : "greet", pc : 5 }, { "context" : "__main__", pc : 12 }, ]

We'd then execute line 6, and after executing that line, our stack would
look like this:

[ { "context" : "greet", pc : 6 }, { "context" : "__main__", pc : 12 }, ]

We're falling off the end of a function at that point, so we'd pop the top
stack frame, as follows:
[ { "context" : "__main__", pc : 12 }, ]

Which means we return to the line after 12, and continue on with line 13
print "see what I mean". That means the '''print "We don't reach here"'''
code isn't executed.

>> * Am I mad? :)
> 
> Yep. :)

Thought so!

Thanks :-)


Michael.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread placid

Jim Segrave wrote:
> In article <[EMAIL PROTECTED]>,
> valpa <[EMAIL PROTECTED]> wrote:
> >I'm a net admin for about 20 unix servers, and I need to frequently
> >telnet on to them and configure them.
> >It is a tiring job to open a xterm and telnet, username, password to
> >each server.
>
> Don't use telnet. it's clumsy and has security issues.

if youre behind a firewall then it shouldnt matter.

>
> Use ssh with RSA or DSA keys. Then you simply do:
>
> ssh [EMAIL PROTECTED]
>
> in an xterm and you are loggedis as user username on server
> machinename. It's vastly more secure and more reliable.
>
> If you're talking about initial setup of a machine (OS installation or
> whatever), our solution was to have a post-install CD or floppy which
> fetched standard server configuration data. This included an ssh
> public key for our ssh-key distribution, so after running the
> post-install disc, we could push out staff ssh-keys and logins were
> available.

I dont think the OP wants to do post-install configuration (i may be
wrong! )  but to change for example some config file.

You should be able to create a dictionary containing username=password,
then iterate over this dictionary and use os.system("xterm -e telnet -u
%s -p %s") where -u is username and -p is password (im not quite sure
if telnet has these arguments or if it works like this too)

Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread faulkner
try pexpect.
http://pexpect.sourceforge.net/

valpa wrote:
> I'm a net admin for about 20 unix servers, and I need to frequently
> telnet on to them and configure them.
> It is a tiring job to open a xterm and telnet, username, password to
> each server.
>
> Can I  do it automatically by python? After that, there have 20 xterm
> consoles opened and telneted to their corresponding servers. Then I
> could start to type command in these xterms.
> 
> Any suggestion appreciate. Much thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread faulkner
try pexpect.
http://pexpect.sourceforge.net/

valpa wrote:
> I'm a net admin for about 20 unix servers, and I need to frequently
> telnet on to them and configure them.
> It is a tiring job to open a xterm and telnet, username, password to
> each server.
>
> Can I  do it automatically by python? After that, there have 20 xterm
> consoles opened and telneted to their corresponding servers. Then I
> could start to type command in these xterms.
> 
> Any suggestion appreciate. Much thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python guru in the Bay Area

2006-07-02 Thread Aahz
In article <[EMAIL PROTECTED]>,
bruce <[EMAIL PROTECTED]> wrote:
>
>is there someone in the Bay Area who knows python, that I can talk to ... I
>have the shell of a real basic app, and I'd like someone who can walk me
>through how to set it up.

While I agree with all the other advice you've been given, if you really
want to try finding someone local:

http://baypiggies.net/
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I saw `cout' being shifted "Hello world" times to the left and stopped
right there."  --Steve Gonedes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP thought experiment: Unix style exec for function/method calls

2006-07-02 Thread Carl Banks
Michael wrote:
> > > def set_name():
> > > name = raw_input("Enter your name! > ")
> > > cexe greet()
> > >
> > > def greet():
> > > print "hello", name
> > >
> > > cexe set_name()
> > > print "We don't reach here"
> > > --
> > >
> > > This would execute, ask for the user's name, say hello to them and then
> > > exit - not reaching the final print "We don't reach here" statement.
> >
> > Only if you were to replace the whole stack.  If you only replace or
> > reuse the top frame, I would think greet would exit and execution would
> > resume right after the point from which set_name was called.  Or am I
> > misunderstanding what you want?
>
> I think you are.
[snip]

I'm sorry; I didn't notice the use of cexe also on the call to
set_name.  So now it makes sense.


Carl Banks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread vasudevram

Just FYI - pexpect is a Python app that works like Expect - which is by
Don Libes and written in TCL. Expect comes with most Linux
distributions and is available for most UNIX / Linux versions from its
web site http://expect.nist.gov/

The expect man page is enough to get started for simple needs, such as
yours appears to be. You might want to play around with the original
Expect a bit and then try out pexpect  - or you could just use Expect
itself for your needs.

HTH
Vasudev
---
Vasudev Ram
Independent software consultant
http://www.geocities.com/vasudevram
PDF conversion toolkit:
http://sourceforge.net/projects/xtopdf
---


faulkner wrote:
> try pexpect.
> http://pexpect.sourceforge.net/
>
> valpa wrote:
> > I'm a net admin for about 20 unix servers, and I need to frequently
> > telnet on to them and configure them.
> > It is a tiring job to open a xterm and telnet, username, password to
> > each server.
> >
> > Can I  do it automatically by python? After that, there have 20 xterm
> > consoles opened and telneted to their corresponding servers. Then I
> > could start to type command in these xterms.
> > 
> > Any suggestion appreciate. Much thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: languages with full unicode support

2006-07-02 Thread Oliver Bandel
Matthias Blume wrote:

> Tin Gherdanarra <[EMAIL PROTECTED]> writes:
> 
> 
>>Oliver Bandel wrote:
>>
>>>こんいちわ Xah-Lee san ;-)
>>
>>Uhm, I'd guess that Xah is Chinese. Be careful
>>with such things in real life; Koreans might
>>beat you up for this. Stay alive!
> 
> 
> And the Japanese might beat him up, too.  For butchering their
> language. :-)

OK, back to ISO-8859-1 :)  no one needs so much symbols,
this is enough: äöüÄÖÜß :)


Ciao,
   Oliver
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python CGI Scripting Documentation

2006-07-02 Thread Alex Martelli
Vlad Dogaru <[EMAIL PROTECTED]> wrote:

> Hello,
> 
> I would like to learn web scripting with Python (sure, everyone uses
> PHP, but I don't like the syntax and Python is more general-purpose
> and... well, I guess you people know the advantages better than me).
> Where can I get a thorough introduction to both CGI and using Python
> for CGI? That includes installing my own web server (at home, for
> testing) and starting from scratch (by that I mean I have near null
> experience with CGI).
> 
> I have tried looking through the source code of MoinMoin, but it's just
> too advanced for me -- I simply don't know where to start. Right now,
> I'll take any and all suggestions. However, please suggest books or
> articles that are up-to-date on Python programming; I'd hate to see
> that I'm studying obsolete texts or the like.

In terms of learning, Steve Holden's "Python Web Programming" is still
unbeatable -- it teaches you just enough of the many underlying
technologies, from HTTP to HTML to relational databases, as well as
Python.  However, it IS an old version of Python (sigh).  But it's very
easy to learn the relatively small enhancements to the Python language
since the time Steve penned his masterpiece... anything that used to
work then still works now, you have better ways to perform many tasks
(particularly thanks to additions to the standard library, and third
party extension modules matured in the meantime) but those are easy to
learn "afterwards" (and meanwhile, a solid understanding of the basics
of, say, HTTP and entity-relation design, will stand you in good stead
for years and years to come!-).  Steve's book is really the best you can
get, for "learning" purposes such as yours.  However...L

If you insist on getting coverage of the latest and greatest version of
Python, you might want to get the 2nd edition of my "Python in a
Nutshell", due out later this month; it strives to cover Python 2.5
(also due out later this month;-) as well as 2.4 (the still-now current
version, on which the new Nutshel focuses), and does have a chapter
specifically on CGI (not much changed from the first edition's, of
course, since CGI itself has not changed much over the years;-).

To have a look at my book (and just about any other O'Reilly book... and
not just O'Reilly either!) for free, subscribe to O'Reilly's "Safari"
online library -- I believe the first two weeks are free, so, as long as
you cancel in time, you should not have to pay a penny for the
privilege; thus, it may be a good idea (I personally like having access
to said library for searches etc, but that's a separate issue).  It will
be a while before the 2nd edition gets online -- but as I said the CGI
part is basically unchanged anyway.

But, talking of web resources...:

A Google search for Python CGI gives you 20 million hits, and quite a
few of those appear to be good tutorials on the subject -- why don't you
give those a try, first?  Sure, most of the pages will be using older
versions of Python -- but most of the differences should be of little
importance. One crucial one: you *DO* want to use the cgitb auxiliary
module to get good tracebacks in case of errors, and older sites may not
mention it -- however, that's pretty simple indeed...:

  import cgitb; cgitb.enable()

just place this line at the very top of your CGI script (after the
"shebang" line and the docstring, heh:-) and you're all set.  Any
further info you need for "advanced" usage of cgitb is in one tiny page
at .


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

2006-07-02 Thread Simon Forman
Nick Vatamaniuc wrote:
> Robert Kern wrote:
> > [EMAIL PROTECTED] wrote:
> > > The same thing goes for the values(). Here most people will argue that
...
> >
> > This part is pretty much a non-starter. Not all Python objects are hashable.
...
> > Also, I may need keys to map to different objects that happen to be equal.
> >
> > --
> > Robert Kern
> >


So, values() can't return a set because of (at least) the two reasons
given above.  And since, as Scott David Daniels pointed out, dicts
support the iterator protocol, you can ask for a set of the keys easily
enough if you want it:

>>> d = dict(a=1, b=2, c=3)
>>> set(d)
set(['a', 'c', 'b'])

So, IMHO, there's not much point to having keys() return a set.


Peace,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a limited set of instanceses of a class

2006-07-02 Thread Alex Martelli
madpython <[EMAIL PROTECTED]> wrote:

> Thanks Alex and Scott for your lead. It would've taken me forever
> trying to figure it out by myself :)
> 
> I am affraid I didn't specify initially one thing and that led to a
> confusion: there is no need to pick an instance from the weakref
> dictionary, just return None if there are already 5 instances. But on
> the other hand if a hardref to an object was deleted, it's place can be
> taken by another one.

And the latter issue is what the use of weakref in both responses was
about.

> Here's what i mean (and where the problem is):
> 
> #build a list of 5 elements
> instList=[]
> for i in range(7):
>   ainst=A()
>   if ainst:
>   instList.append(ainst)

Note that this is quite sloppy:

-- test "if ainst is None:" -- no excuse to use just "if ainst:"
-- at the end of the loop ainst remains bound -- "del ainst" to avoid
   ainst being an extra reference to the instance

neither of these explains your bug, but -- just tighten up your code,
it's a good idea!-)

> 
> for i in range(5):
>   instList.remove(instList[0]) #here the hardref is deleted

SUPER sloppy!  Just "del instList[0]" for the same effect much better
obtained.

>   ainst=A()
>   while not ainst:
>   #make shure that ainst is not NoneType

Again, "while ainst is None:" would be far better.

>   gc.collect()
>   time.sleep(1)   #wait 1 sec for gc() to clean the memory

Useless, gc.collect() is synchronous *AND* only cleans up CYCLIC garbage
anyway -- unless instances of A have reference loops, both lines are
useless (the sleep is useless in ANY case).

>   ainst=A()   #try again
>   instList.append(ainst) #new object added
> 
> the priblem is that ~3 out of 10 times the test part run into infinite
> loop because of unsatisfied condition (while not ainst:) - memory
> cannot be freed therefore new instance of A isn't permitted.

Your test code below does NOT do what your code here does!  Instead it
removes (in the worst possible way, rather than cleanly, but, no matter)
a RANDOM reference -- which may happen to be the same as "item" had left
over from the previous run... because of a printing loop that is in your
sample below and not here... which is where the sloppiness catches up on
you.  Specifically, look at this code from the sample that you had
below:

> #delete and recreate an arbitrary element in the instList
> for i in range(len(instList)):
> instList.remove(instList[random.choice(range(len(instList)))])
> ainst=A()
> while not ainst:#here is an unstable part
> ainst=A()   #sometimes the loop becomes infinite
> print gc.collect()  #decpite the explicit call for gc() to start
> time.sleep(1)
> print "*", len(instList), len(A._weakrefdict)
> instList.append(ainst)
> for item in instList:
> print item.getId()," -- ",item.instCounter
> #print "---> ",item
> print ""

after the printing loop, name 'item' remains bound to the object that is
last element of instList -- so if that one just happens to be the
element you remove in that horrid first line of the main (outer) loop, 5
instances of class A nevertheless remain alive and therefore ainst will
be None forevermore, despite all the useless calls to gc.collect and
sleep.

A decent way to code this functionality would be:

# delete and recreate an arbitrary element in the instList
for i in range(len(instList)):
del instList[random.randrange(len(instList))]
instList.append(A())
for item in instList:
print item.getId()," -- ",item.instCounter
del item
print ""

It would be nice to also print len(instList) and the length of the
weakref dictionary of class A, to doublecheck things, but you've made
life extremely hard for yourself by naming the latter with TWO leading
underscores instead of one, thus asking Python to name-mangle it to make
it very inconvenient to access.  Avoid the two-leading-underscores
construct (use just ONE leading underscore -- no mangling, no problems)
unless and until you are positive that you know exactly what you're
doing and are certain that you need the two underscores in a given
specific case -- do *NOT* "default" to using two underscores and make
life uselessly hard for yourself in terms of introspection and
debugging.

And, read up on such issues as "del somelist[index]" being WAY better
than "somelist.remove(somelist[index])" and the way names, references,
objects and garbage collection work in Python...


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Challenge - thesamet unreachable?

2006-07-02 Thread [EMAIL PROTECTED]
If anyone has a way to contact thesamet, please tell him to check his
private messages at the Python Challenge website; I have a couple of
ideas for more challenges.

Cheers all.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyPy and constraints

2006-07-02 Thread Ziga Seilnacht
Paddy wrote:
> I followed the recent anouncement of version 0.9 of PyPi and found out
> that there was work included on adding constraint satisfaction solvers
> to PyPy:
>   http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html
>
> I was wondering if this was a possibiity for "mainstream" python, and
> wether the the algorithms used could handle the kind of use mentioned
> here:
>
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/d297170cfbf1bb34/d4773320e3417d9c?q=constraints+paddy3118&rnum=3#d4773320e3417d9c
>
> Thanks, Paddy.

See: http://www.logilab.org/projects/constraint

Hope this helps,
Ziga

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread Network Ninja

valpa wrote:
> I'm a net admin for about 20 unix servers, and I need to frequently
> telnet on to them and configure them.
> It is a tiring job to open a xterm and telnet, username, password to
> each server.
>
> Can I  do it automatically by python? After that, there have 20 xterm
> consoles opened and telneted to their corresponding servers. Then I
> could start to type command in these xterms.


I often have to add users/delete local user accounts on routers and
switches. Each account is a local account, and I got tired of it. My
very first python program was created to use the telnetlib, and either
add, delete, or show a list of user accounts. It was very effective,
because it would change the same accounts on each router and switch.
Saved me a bunch of time, and got me hooked on python. If you are not
concerned about security, the telnetlib in python will help you.
Otherwise, use ssh, as it is more secure. You can even impliment
public/private keys for password-less log on. If you want some help
with the code for the telnetlib, let me know.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a limited set of instanceses of a class

2006-07-02 Thread madpython
Thanks, Alex, again. The lesson has been taught. I appreciate very much
you spent time trying to help. Indeed the culprit of that infrequent
infinite loops was that bound reference "item" in the printing
loop. But frankly i thought that it only existed inside that loop.
Apparently I was wrong and glad that it was revealed.
I guess unless there is something  to add here the problem is solved
and subject is closed. Thanks everyone who took their time to ponder on
it. I hope it was as much educational for you as it was for me.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I have 100 servers which need a new backup server added to a text file, and then the backup agent restarted.

2006-07-02 Thread Ove Pettersen
gavino wrote:
> This seems easy but I have been asking tcl and python IRC chat all day
> and no one gave an answer.
> I have 100 servers which need a new backup server added to a text file,
>  and then the backup agent restarted.
> If I have a list of the servers, all with same root password, and the
> connection is ssh.
> How do I connect to the server, cat the line to the config file, stop
> adn start the agent, and then do same to next server in list and
> iterate through the 100 servers. 
> What script would allow this?
> 

I wouldn't use python at all (like swearing on this list???)  simple 
shell-command is more than sufficient.

for server in "server1 server2 server3  server100"
do
ssh [EMAIL PROTECTED] "(echo "new line" >> config.file; stop-command ; 
sleep 5 ; start-command)"
done

I would however have extended the procedure with a few more checks...
Like:
* only add new line to config-file if it isn't present
* only do restart if config-file was modified

Regards,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [with Python3000 in mind]

2006-07-02 Thread Terry Reedy
The meaning of dict.keys, etc, will not change for the 2.x series.  For 
3.0, I believe that Guido already intends that .keys() no longer return a 
separate list.  For one thing, a major, if not the main use, of the method 
is for iteration, as in 'for keys in d.keys():'.  For this, creating and 
them discarding a separate list is inefficient and, in a sense, silly.

One option is to make .keys be what .iterkeys is today.  Another, more 
recent, is to make .keys return a new iterable dict view object, details 
not yet worked out.  Either way, one would make an independent set or list 
with set(d.keys()) or list(d.keys)).

Terry Jan Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


wanted: framework for creating nice step by step graphical visualisations of running Python code

2006-07-02 Thread Claudio Grondi

Today I bumped by chance into explaining what algorithms do by using 
animation (Java applets):
   http://www-sr.informatik.uni-tuebingen.de/~buehler/BM/BM1.html

Is there any tool in Python (except pyGame, Tkinter or other general 
purpose visualization tools) I am not aware of which would make it easy 
to create a similar, animated run through Python script code?

A free debugging tool capable of stepping line by line through Python 
code showing values of selected objects will do as a first approach, but 
it would be nice to be able to output also some graphics and/or text 
like it is done in the mentioned above example at pre-defined points in 
code called there
   /* visualisation step */

Any hints towards getting or constructing such a framework are welcome.

Claudio Grondi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I have 100 servers which need a new backup server added to a text file, and then the backup agent restarted.

2006-07-02 Thread Petr Jakeš
g> This seems easy but I have been asking tcl and python IRC chat all day
g> and no one gave an answer.
g> I have 100 servers which need a new backup server added to a text file,
g>  and then the backup agent restarted.
g> If I have a list of the servers, all with same root password, and the
g> connection is ssh.
g> How do I connect to the server, cat the line to the config file, stop
g> adn start the agent, and then do same to next server in list and
g> iterate through the 100 servers. 
g> What script would allow this?

Maybe webmin could help. http://www.webmin.com/
You can manage cluster of servers at once.

Petr Jakes

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a limited set of instanceses of a class

2006-07-02 Thread Alex Martelli
madpython <[EMAIL PROTECTED]> wrote:

> Thanks, Alex, again. The lesson has been taught. I appreciate very much
> you spent time trying to help. Indeed the culprit of that infrequent
> infinite loops was that bound reference "item" in the printing
> loop. But frankly i thought that it only existed inside that loop.
> Apparently I was wrong and glad that it was revealed.

Right -- a loop per se (be it a while loop or a for loop), just like an
if statement or a try statement, is NOT a separate scope from the code
around it (neither is a list comprehension); _functions_ are separate
scopes, and so are genexps.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread [EMAIL PROTECTED]
I used this _EXACT_ solution(copied below) at work a month ago, to
start 20ish programs, each with different settings.  In this case I HAD
to use telnet for some of them, because they were on an embedded
machine, 4 of them used SSH(across the internet), and the rest were
local programs.  It worked flawlessly each time (every restart of the
network... which was quite often in this case).  There may be more
integrated solutions which solve the problem, but expect is rediculousy
easy to use, and is very deterministic as long as the commands work.
If the commands fail to work (such as someone deletes your program),
debugging is rather difficult, but at least you have a full dump of
everything sent by the server (because pexpect prints it all to the
screen).  Also, once the connection is open, you can call
conn.interact() and it will make the terminal interactive, just like
any other shell.


vasudevram wrote:
> Just FYI - pexpect is a Python app that works like Expect - which is by
> Don Libes and written in TCL. Expect comes with most Linux
> distributions and is available for most UNIX / Linux versions from its
> web site http://expect.nist.gov/
>
> The expect man page is enough to get started for simple needs, such as
> yours appears to be. You might want to play around with the original
> Expect a bit and then try out pexpect  - or you could just use Expect
> itself for your needs.
>
> HTH
> Vasudev
> ---
> Vasudev Ram
> Independent software consultant
> http://www.geocities.com/vasudevram
> PDF conversion toolkit:
> http://sourceforge.net/projects/xtopdf
> ---
>
>
> faulkner wrote:
> > try pexpect.
> > http://pexpect.sourceforge.net/
> >
> > valpa wrote:
> > > I'm a net admin for about 20 unix servers, and I need to frequently
> > > telnet on to them and configure them.
> > > It is a tiring job to open a xterm and telnet, username, password to
> > > each server.
> > >
> > > Can I  do it automatically by python? After that, there have 20 xterm
> > > consoles opened and telneted to their corresponding servers. Then I
> > > could start to type command in these xterms.
> > > 
> > > Any suggestion appreciate. Much thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: xpath question

2006-07-02 Thread bruce
hi

is there anyone with XPath expertise here? i'm trying to figure out if
there's a way to use regex expressions with an xpath query? i've seen
references to the ability to use regex and xpath/xml, but i'm not sure how
to do it...

i have a situation where i have something like:
 /html/table//[EMAIL PROTECTED]'foo']

is it possible to do soomething like [EMAIL PROTECTED]/fo/] so i'd match the 
class
attribute with fo

i'm trying to parse HTML/Web docs...

thanks

-bruce


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xpath question

2006-07-02 Thread Simon Forman
bruce wrote:
> hi
>
> is there anyone with XPath expertise here? i'm trying to figure out if
> there's a way to use regex expressions with an xpath query? i've seen
> references to the ability to use regex and xpath/xml, but i'm not sure how
> to do it...
>
> i have a situation where i have something like:
>  /html/table//[EMAIL PROTECTED]'foo']
>
> is it possible to do soomething like [EMAIL PROTECTED]/fo/] so i'd match the 
> class
> attribute with fo
>
> i'm trying to parse HTML/Web docs...
>
> thanks
>
> -bruce

I'll take this one...

Dude,  this is a *python* mailing list, not an xml/xpath/regex one.  In
addition, the regex syntax you're using above (~=/fo/) looks like
*perl* code--  but I wouldn't know 'cause I don't use perl myself.

Now it's entirely possible that there are *many* people here that are
xml/xpath/regex Kung Fu Masters,  *and* it's entirely possible that one
or more of them are about to answer your question informatively and in
exhaustive detail.  It's also entirely possible that this is the most
friendly and informative reply that you're going to get, here.


Try a more appropriate newsgroup, and good luck.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Computer Industry Workers May Face Cancer Risks

2006-07-02 Thread Cydrome Leader
In comp.unix.solaris [EMAIL PROTECTED] wrote:
> Computer Industry Workers May Face Cancer Risks
> 
> http://www.studyandjobs.com/Comp_worker_cancer.html
> 
> or visit
> http://www.studyandjobs.com/Cancer.html
> 
> Regards

worthless add banner site
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: xpath question

2006-07-02 Thread bruce
simon..

you may not.. but lot's of people use python and xpath for html/xml
functionality.. check google "python xpath"...

later..


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Simon Forman
Sent: Sunday, July 02, 2006 2:10 PM
To: python-list@python.org
Subject: Re: xpath question


bruce wrote:
> hi
>
> is there anyone with XPath expertise here? i'm trying to figure out if
> there's a way to use regex expressions with an xpath query? i've seen
> references to the ability to use regex and xpath/xml, but i'm not sure how
> to do it...
>
> i have a situation where i have something like:
>  /html/table//[EMAIL PROTECTED]'foo']
>
> is it possible to do soomething like [EMAIL PROTECTED]/fo/] so i'd match the 
> class
> attribute with fo
>
> i'm trying to parse HTML/Web docs...
>
> thanks
>
> -bruce

I'll take this one...

Dude,  this is a *python* mailing list, not an xml/xpath/regex one.  In
addition, the regex syntax you're using above (~=/fo/) looks like
*perl* code--  but I wouldn't know 'cause I don't use perl myself.

Now it's entirely possible that there are *many* people here that are
xml/xpath/regex Kung Fu Masters,  *and* it's entirely possible that one
or more of them are about to answer your question informatively and in
exhaustive detail.  It's also entirely possible that this is the most
friendly and informative reply that you're going to get, here.


Try a more appropriate newsgroup, and good luck.

--
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


newbie graphing recommendations ?

2006-07-02 Thread Adam

Where should a py newbie start to do some 2D graphs on screen ? 

PythonGraphApi, 
Gato, looks interesting 
pygraphlib, 
matplotlib, 

is there a best native Python place to start ? 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I have 100 servers which need a new backup server added to a text file, and then the backup agent restarted.

2006-07-02 Thread Michael Abbott
Ove Pettersen <[EMAIL PROTECTED]> wrote:
> for server in "server1 server2 server3  server100"; do

Two comments:

1.  Leave out the quotes(!)

2.  Either iterate as
   for server in $(seq -fserver%g 100); do
or, probably better
   for server in $(cat server-list); do
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wanted: framework for creating nice step by step graphical visualisations of running Python code

2006-07-02 Thread bearophileHUGS
I remember Gato:
http://gato.sourceforge.net/
It animates only algorithms on graphs, but it seems a starting point,
and it works.

I vaguely remember another system, but probably not very good.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie graphing recommendations ?

2006-07-02 Thread Scott David Daniels
Adam wrote:
> Where should a py newbie start to do some 2D graphs on screen ? 
> PythonGraphApi, 
> Gato, looks interesting 
> pygraphlib, 
> matplotlib, 
> is there a best native Python place to start ? 

Check VPython (maybe least learning effort to first usable graphs).
Also look at PyGame if you want to paint screens.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: languages with full unicode support

2006-07-02 Thread Matthias Blume
Oliver Bandel <[EMAIL PROTECTED]> writes:

>>>Oliver Bandel wrote:
>>>
こんいちわ Xah-Lee san ;-)
>>>
>>>Uhm, I'd guess that Xah is Chinese. Be careful
>>>with such things in real life; Koreans might
>>>beat you up for this. Stay alive!
>> And the Japanese might beat him up, too.  For butchering their
>> language. :-)
>
> OK, back to ISO-8859-1 :)  no one needs so much symbols,
> this is enough: äöüÄÖÜß :)

There are plenty of people who need such symbols (more people than
those who need ß, btw).

Matthias

PS: It should have been こんにちは.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PyPy and constraints

2006-07-02 Thread Paddy

Ziga Seilnacht wrote:
> Paddy wrote:
> > I followed the recent anouncement of version 0.9 of PyPi and found out
> > that there was work included on adding constraint satisfaction solvers
> > to PyPy:
> >   http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html
> >
> > I was wondering if this was a possibiity for "mainstream" python, and
> > wether the the algorithms used could handle the kind of use mentioned
> > here:
> >
> > http://groups.google.com/group/comp.lang.python/browse_frm/thread/d297170cfbf1bb34/d4773320e3417d9c?q=constraints+paddy3118&rnum=3#d4773320e3417d9c
> >
> > Thanks, Paddy.
>
> See: http://www.logilab.org/projects/constraint
>
> Hope this helps,
> Ziga

Thanks Ziga,
i had already had a look at that package and its very good.
But, I guess what is different about what is used in the Verification
of electronic designs is the notion of randomized variables.
if you declared a randomized variable R1 and said it was constrained
such that
 0<=R1 <256
Then you could generate values of R1 which would have successive
PSEUDO-RANDOM values between 0 and 255 inclusive.
If you introduced randomized variable R2, with the constraints:
  R2 >=0
  R1*R2 <512

Then you could generate R1,R2 pairs that satisfy the relations and
appear pseudo-random.

Some Electronic Design Automation constraint solvers might generate all
solutions before epeating. but this is not necessary.

The idea is that you electronic designs have a huge state space to test
and so cannot be exaustively tested. If you write a deterministic test
then you are directly loading your test with bias about how you think
the design works or should be tested. With constrained random
generation you work the other way by trying to constrain test segments
to create valid tests but due to the randomness involved, the tests
generated may exercise the design in valid ways that a deterministic
test writer would not have thought of.
The method does work in practice. I'd just like to know if my favourite
language might be changing to have this capability.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging error with RotatingFileHandler

2006-07-02 Thread Vinay Sajip

flupke wrote:

> > -> The rename fails for some reason.

I would dig a little deeper to find out what the reason is. After all,
on the face of it, there's no obvious reason it should fail. The
"permission denied" indicates perhaps that some other process or thread
is keeping that file open?

I've fixed (AFAICT) both the crash at shutdown and the buggy exception
handling, in the Python subversion repository. You can download the
latest from here and try it.

http://svn.python.org/view/python/trunk/Lib/logging/

Regards,

Vinay Sajip

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dictionary .keys() and .values() should return a set [with Python3000 in mind]

2006-07-02 Thread Delaney, Timothy (Tim)
[EMAIL PROTECTED] wrote:

> This has been bothering me for a while. Just want to find out if it
> just me or perhaps others have thought of this too: Why shouldn't the
> keyset of a dictionary be represented as a set instead of a list?

There has been much discussion of this on the Python-3000 mailing list.
Suggestings included making keys(), etc return an iterator, and getting
rid of iterkeys(), etc.

The eventual consensus was that keys(), etc should return views on the
dictionary. These views would be re-iterable and will have basically the
same behaviour as the lists returned from keys(), etc. However, such a
view could have O(1) __contains__ behaviour, and would not incur the
overhead of creating a list and populating it - they would be backed by
the dictionary. Of course, this introduces the issue of concurrent
modification, but you can always get an independent copy by calling
list(dict.keys()).

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wanted: framework for creating nice step by step graphical visualisations of running Python code

2006-07-02 Thread Claudio Grondi
[EMAIL PROTECTED] wrote:
> I remember Gato:
> http://gato.sourceforge.net/
> It animates only algorithms on graphs, but it seems a starting point,
> and it works.
> 
> I vaguely remember another system, but probably not very good.
> 
> Bye,
> bearophile
> 
Yes, I have noticed Gato already before, but was not able to find my way 
into it - I am missing a kind of tutorial explaining what it is all 
about - the description of available classes or demos don't tell me much 
about it, so I have no idea how to start - is there any tutorial out 
there explaining it from the very beginning what is it for, how it does 
it and why?
By the way: it seems to be very slow on my 3 GHz Pentium 4 system ...

Any other hints?

Claudio
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and interfaces

2006-07-02 Thread Rene Pijlman
[EMAIL PROTECTED]:
>In python , how to implement interface like the above? 

Interfaces are lacking in Python, but an even more generic proposal is on
its way:
http://www.artima.com/weblogs/viewpost.jsp?thread=155123

In the mean time, interfaces have already been implemented in Zope 3:
http://www.zope.org/Products/ZopeInterface

-- 
René Pijlman

"To find out what you can do with interfaces, see the interface interface,
IInterface in the IInterface module."
- Comment in Zope's Interface/__init__.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and interfaces

2006-07-02 Thread Rene Pijlman
Bruno Desthuilliers:
>Java interfaces are a workaround

Troll alert.
-- 
http://mail.python.org/mailman/listinfo/python-list


python function defs/declarations

2006-07-02 Thread bruce
hi..

the docs state that the following is valid...

def foo():
 i = 2
 print "i = "i

print "hello"
foo()


is there a way for me to do this..

print "hello"
foo()

def foo():
 i = 2
 print "i = "i

ie, to use 'foo' prior to the declaration of 'foo'

thanks

-bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


Time out question

2006-07-02 Thread DarkBlue
My application makes several connections to
a remote database server via tcp/ip.
Usually all is fine,but occasionally the server is
down or the internet does not work and then there is
the 30 sec to several minutes timeout wait for the
tcp to give up.
Is there anything I can do without using 
threads,sockets,twisted etc. to have following :

pseudocode :

 try for 10 seconds
   if database.connected :
do your remote thing
 except raise after 10 seconds
   abort any connection attempt
   do something else 


Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python function defs/declarations

2006-07-02 Thread Alex Martelli
bruce <[EMAIL PROTECTED]> wrote:

> hi..
> 
> the docs state that the following is valid...
> 
> def foo():
>  i = 2
>  print "i = "i
> 
> print "hello"
> foo()
> 
> 
> is there a way for me to do this..
> 
> print "hello"
> foo()
> 
> def foo():
>  i = 2
>  print "i = "i
> 
> ie, to use 'foo' prior to the declaration of 'foo'

There are no declarations in Python.  "def" is an executable statement:
when executes it binds a new function object to the given name.

So, your request is like asking to do, say:

print "hello"
print wap

wap = "world"

At the time you use name wap, nothing is bound to it; the fact that
something would later be bound to it (if the binding statement, here an
assignment but that's exactly as much of an executable statement as a
def!) is pretty clearly irrelevant.  Having a clear idea about these
issues is why it's important to remember the distinction between
executable statements (including def, class, assignments, ...) and
declarations (which Python does not have).

You can probably wrap your code in a function, and call it at the end:

def main():
  print "hello"
  foo()

def foo(): ...whatever...

main()


By the time the body of main executes, "def foo" has already executed,
so global name foo is happily bound and everything works fine.

Wrapping most substantial code inside functions is VERY advisable anyway
-- just put just about all the code you'd like to have at module top
level (except for def, class and assignments to "module constants") into
a function (conventionally named main) and call that function at the
very end of the module (ideally within an "if __name__=='__main__":"
guard, but that's a different issue!).


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time out question

2006-07-02 Thread Alex Martelli
DarkBlue <[EMAIL PROTECTED]> wrote:

> My application makes several connections to
> a remote database server via tcp/ip.
> Usually all is fine,but occasionally the server is
> down or the internet does not work and then there is
> the 30 sec to several minutes timeout wait for the
> tcp to give up.
> Is there anything I can do without using 
> threads,sockets,twisted etc. to have following :
> 
> pseudocode :
> 
>  try for 10 seconds
>if database.connected :
> do your remote thing
>  except raise after 10 seconds
>abort any connection attempt
>do something else 

Sure, see function setdefaulttimeout in module socket.  Just call it as
you wish before trying the DB connection and catch the resulting
exception.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xpath question

2006-07-02 Thread Simon Forman
bruce wrote:
> simon..
>
> you may not.. but lot's of people use python and xpath for html/xml
> functionality.. check google "python xpath"...
>
> later..
>
...
> > i have a situation where i have something like:
> >  /html/table//[EMAIL PROTECTED]'foo']
> >
> > is it possible to do soomething like [EMAIL PROTECTED]/fo/] so i'd match 
> > the class
> > attribute with fo
> >


So I did some checking, starting with the google search you suggested,
and I found out that lxml, 4Suite, and Amara (which is apparently based
on 4Suite somehow) all seem to be capable of doing what you're talking
about.  I don't know how to do it with lxml, but I bet the people on
the lxml mailing list would be happy to explain it to you.  As for
Amara and 4Suite I think it might be as simple as saying "Match(your
regex here in python re module form)" in your Xpath statement..


In the meantime, you could just use Xpath to extract a superset of the
elements you're interested in and then filter them with a re.Match
object.


I avoid xml if I can help it...   My new favorite HTML editor, however,
is python and ElementTree...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xpath question

2006-07-02 Thread uche . ogbuji
bruce wrote:
> is there anyone with XPath expertise here? i'm trying to figure out if
> there's a way to use regex expressions with an xpath query? i've seen
> references to the ability to use regex and xpath/xml, but i'm not sure how
> to do it...
>
> i have a situation where i have something like:
>  /html/table//[EMAIL PROTECTED]'foo']
>
> is it possible to do soomething like [EMAIL PROTECTED]/fo/] so i'd match the 
> class
> attribute with fo
>
> i'm trying to parse HTML/Web docs...

4Suite [1] supports regex in XPath using the EXSLT community standard's
regex module [2].  It would be something like:

[re:match(@class, 'fo.*']

With the re prefix set as required by the EXSLT module.

[1] http://4Suite.org
[2] http://www.exslt.org/regexp/

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beautifulsoup .vs tidy

2006-07-02 Thread uche . ogbuji
bruce wrote:
> hi paddy...
>
> that's exactly what i'm trying to accomplish... i've used tidy, but it seems
> to still generate warnings...
>
>  initFile -> tidy ->cleanFile -> perl app (using xpath/livxml)
>
> the xpath/linxml functions in the perl app complain regarding the file. my
> thought is that tidy isn't cleaning enough, or that the perl xpath/libxml
> functions are too strict!
>
> which is why i decided to see if anyone on the python side has
> experienced/solved this problem..

FWIW here's my usual approach:

http://copia.ogbuji.net/blog/2005-07-22/Beyond_HTM

Personally, I avoid Tidy.  I've too often seen it crash or hang on
really bad HTML.  TagSoup seems to be built like a tank.  I've also
never seen BeautifulSoup choke, but I don't use it as much as TagSoup.

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Amara: Where's my attribute?

2006-07-02 Thread uche . ogbuji
AdSR wrote:
> Hi,
>
> I'm having a problem with the Amara toolkit. Try this:
>
> >>> from amara import binderytools
> >>> raw = 'http://example.com/namespace"; 
> >>> xmlns:pq="http://pq.com/ns2"/>'
> >>> rwd = binderytools.bind_string(raw)
> >>> print rwd.xml()
> 
> http://pq.com/ns2"/>
>
> What happened to the xmlns attribute? Does anyone know a solution to
> this? The only workaround I found is to:
>
> >>> rwd.test.xml_set_attribute(u'xmlns', u'http://example.com/namespace')
> u'xmlns'
> >>> print rwd.xml()
> 
> http://pq.com/ns2";
> xmlns="http://example.com/namespace"/>
>
> but it only helps if you know what to patch.
>
> My setup:
>
> Python 2.4.3
> 4Suite 1.0b3
> Amara 1.0
>
> I see that people have reported similar problems with other XML
> toolkits, so I guess this is a general namespace ugliness.

What is the actual problem you're trying to solve?  If you just want to
force a namespace declaration in output (this is sually to support
QNames in content) the most well-known XML hack is to create a dummy
attribute with the needed prefix and namespace.  But this does not work
when you're trying to force a default namespace declaration.  Then
again, you generally can't use QNames in content with a default
namespace declaration.  So my guess is that you somehow got way off the
rails in your problem-solving, and you'll need to provide mre
background if you want help.

BTW, I recommend upgrading to Amara 1.1.7.  That branch will soon be
1.2, and I consider it more mature than 1.0 at this point.  The API's
also easier:

>>> import amara
>>> rwd = amara.parse('http://example.com/namespace"; 
>>> xmlns:pq="http://pq.com/ns2"/>')


--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

-- 
http://mail.python.org/mailman/listinfo/python-list


Turning a callback function into a generator

2006-07-02 Thread Kirk McDonald
Let's say I have a function that takes a callback function as a 
parameter, and uses it to describe an iteration:

def func(callback):
 for i in [1, 2, 3, 4, 5]:
 callback(i)

For the sake of argument, assume the iteration is something more 
interesting than this which relies on the callback mechanism. The 
function is an existing interface, and I cannot change it.

I want to somehow, in some way, provide an iteration interface to this 
function. Thoughts?

-Kirk McDonald
-- 
http://mail.python.org/mailman/listinfo/python-list


how to stop python...

2006-07-02 Thread bruce
hi...

perl has the concept of "die". does python have anything similar. how can a
python app be stopped?

the docs refer to a sys.stop.. but i can't find anything else... am i
missing something...

thanks

-bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to stop python...

2006-07-02 Thread Tim Peters
[bruce]
> perl has the concept of "die". does python have anything similar. how can a
> python app be stopped?
>
> the docs refer to a sys.stop.

Python docs?  Doubt it ;-)

> but i can't find anything else... am i missing something...

>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).



Of course there's nothing to stop you from catching SystemExit either
-- it's just another exception, but one that happens to shut down the
interpreter in the specified way if it isn't caught & handled.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to stop python...

2006-07-02 Thread Alex Martelli
bruce <[EMAIL PROTECTED]> wrote:

> hi...
> 
> perl has the concept of "die". does python have anything similar. how can a
> python app be stopped?
> 
> the docs refer to a sys.stop.. but i can't find anything else... am i
> missing something...

import sys

sys.exit()


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to stop python...

2006-07-02 Thread Simon Forman
bruce wrote:
> hi...
>
> perl has the concept of "die". does python have anything similar. how can a
> python app be stopped?
>
> the docs refer to a sys.stop.. but i can't find anything else... am i
> missing something...
>
> thanks
>
> -bruce

What you want is sys.exit()
See: http://docs.python.org/lib/module-sys.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [with Python3000 in mind]

2006-07-02 Thread Paul Rubin
"Delaney, Timothy (Tim)" <[EMAIL PROTECTED]> writes:
> The eventual consensus was that keys(), etc should return views on the
> dictionary. These views would be re-iterable and will have basically the
> same behaviour as the lists returned from keys(), etc. However, such a
> view could have O(1) __contains__ behaviour, and would not incur the
> overhead of creating a list and populating it - they would be backed by
> the dictionary. Of course, this introduces the issue of concurrent
> modification, but you can always get an independent copy by calling
> list(dict.keys()).

Wait a sec, you're saying

  k0 = d.keys()
  d['whee'] = 'parrot'# this can change k0???

That sounds broken.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dictionary .keys() and .values() should return a set [withPython3000 in mind]

2006-07-02 Thread Delaney, Timothy (Tim)
Paul Rubin wrote:

> "Delaney, Timothy (Tim)" <[EMAIL PROTECTED]> writes:
>> The eventual consensus was that keys(), etc should return views on
>> the dictionary. These views would be re-iterable and will have
>> basically the same behaviour as the lists returned from keys(), etc.
>> However, such a view could have O(1) __contains__ behaviour, and
>> would not incur the overhead of creating a list and populating it -
>> they would be backed by the dictionary. Of course, this introduces
>> the issue of concurrent modification, but you can always get an
>> independent copy by calling list(dict.keys()).
> 
> Wait a sec, you're saying
> 
>   k0 = d.keys()
>   d['whee'] = 'parrot'# this can change k0???
> 
> That sounds broken.

That's the problem with views. You either take a snapshot of the current
state, or you deal with the backing store changing. Java's solution is
to raise a ConcurrentModificationException when it determines this has
happened (with lots of weasel words about no guarantees).

If you want an independent data set, you have to take a snapshot. For
the above, that's doing:

k0 = list(d.keys())

or

k0 = set(d.keys())

depending on what behaviour you want.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to stop python...

2006-07-02 Thread Paul McGuire
"bruce" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> hi...
>
> perl has the concept of "die". does python have anything similar. how can
a
> python app be stopped?
>
> the docs refer to a sys.stop.. but i can't find anything else... am i
> missing something...
>
> thanks
>
> -bruce
>
(From the interactive Python prompt:)

import sys
dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__st
din__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names'
, 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook',
'dllhand
le', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix',
'executab
le', 'exit', 'getcheckinterval', 'getdefaultencoding',
'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'hexversion',
'maxint',
 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cach
e', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile',
'setre
cursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',
'version_info
', 'warnoptions', 'winver']

(Hmmm, no mention of "stop", but perhaps "exit"???)

help(sys.exit)

Help on built-in function exit in module sys:

exit(...)
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).


sys.exit()

Voila!

and now this from the "What's new in Python 2.5":
---
In the interactive interpreter, quit and exit have long been strings so that
new users get a somewhat helpful message when they try to quit:

>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
In Python 2.5, quit and exit are now objects that still produce string
representations of themselves, but are also callable. Newbies who try quit()
or exit() will now exit the interpreter as they expect. (Implemented by
Georg Brandl.)

---

So from the ">>>" Python prompt, instead of ^D to exit, one can type quit()
or exit().  Or if sys has been imported, sys.exit().  From within a script,
one can call sys.exit().

-- Paul




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [withPython3000 in mind]

2006-07-02 Thread Paul Rubin
"Delaney, Timothy (Tim)" <[EMAIL PROTECTED]> writes:
> If you want an independent data set, you have to take a snapshot. For
> the above, that's doing:
> 
> k0 = list(d.keys())

I don't understand.  Why have .keys() at all, if it doesn't get you
an independent data set?  If all you want is to iterate through the
dict, you can already do that:

  for k in d: 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension

2006-07-02 Thread a
hey guys
this is gr8
but in cheetah
i use
for test in $ix
$test.url
end for
to iterate thru loop

now how do i iterate feed_list and feed_id along with i,
thanks a lot

N = [(ix.url, ix.id) for ix in feeds_list_select]

feed_list, feed_id = zip(*N)

or just

feed_list, feed_id = zip(*[(ix.url, ix.id) for ix in
feeds_list_select])

Simon Forman wrote:
> a wrote:
> > hi simon thanks for your reply
>
> You're most welcome
>
>
> > what if i want to do this
> > feed_list=[]
> > feed_id=[]
> > for ix in feeds_list_select:
> > global feeds_list
> > global feeds_id
> > feeds_list.append(ix.url)
> >feeds_id.append(ix.id)
> >
> > ie not one variable but more variables
> > thanks
>
> in a case like this I would usually reach for the zip() function, with
> the "varargs" * calling pattern
>
> N = [(ix.url, ix.id) for ix in feeds_list_select]
>
> feed_list, feed_id = zip(*N)
>
>
> or just
>
> feed_list, feed_id = zip(*[(ix.url, ix.id) for ix in
> feeds_list_select])
>
>
> btw, please note that the global statements in your example are
> unnecessary..  *totally* unnecessary.  :-D

-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter function variable passing

2006-07-02 Thread arvind
How to pass the variables defined inside the function to the another
function on click event of the button in Tkinter?
pleas send me a sample code if anybody has it.
thanx

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "valpa" <[EMAIL PROTECTED]> wrote:

>I'm a net admin for about 20 unix servers, and I need to frequently
>telnet on to them and configure them.
>It is a tiring job to open a xterm and telnet, username, password to
>each server.

Do you need to replicate identical configurations to all the servers?

If so, perhaps you're approaching this the wrong way. A better solution 
might be to look at replicating the config files directly to all 
machines (using rsync, scp etc), rather than editing them in situ on 
every single one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I do it using python?? about xterm and telnet

2006-07-02 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "placid" <[EMAIL PROTECTED]> wrote:

>Jim Segrave wrote:
>
>> Don't use telnet. it's clumsy and has security issues.
>
>if youre behind a firewall then it shouldnt matter.

Still not a good idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.stdin and two CTRL-Ds

2006-07-02 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 John Machin <[EMAIL PROTECTED]> wrote:

>On 2/07/2006 3:48 PM, Lawrence D'Oliveiro wrote:
>> In article <[EMAIL PROTECTED]>,
>>  John Machin <[EMAIL PROTECTED]> wrote:
>> 
>>> -u unbuffers sys.stdout 
>>> and sys.stderr (and makes them binary, which wouldn't be a good idea on 
>>> a Windows box).
>> 
>> Why not?
>
>If binary, '\n' would appear as LF alone rather than CR LF.

Why should that matter? I thought Windows (the NT line) was 
POSIX-compliant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter function variable passing

2006-07-02 Thread Fredrik Lundh
arvind wrote:

> How to pass the variables defined inside the function to the another
> function on click event of the button in Tkinter?

 def the_function(master):

 variable = ...

 def callback():
 print variable

 b = Button(master, command=callback)



-- 
http://mail.python.org/mailman/listinfo/python-list