Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Marc 'BlackJack' Rintsch
On Wed, 03 Sep 2008 01:23:47 -0400, Derek Martin wrote:

 On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote:
 The subprocess module is also supposed to replace os.system and
 os.spawn*, neither of which involve opening pipes.
 
 Uh... it's a replacement for os.popen(), which -- guess what -- opens
 pipes.

From the documentation:

subprocess - Subprocesses with accessible I/O streams

This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.  This module
intends to replace several other, older modules and functions, like:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

If it weren't called `Popen` but `Spawn` instead I guess you would argue 
that it *must* be `Spawn` because it spawns processes and even it is not 
using `spawn*()` under the hood it uses the concept of spawn with some 
extras.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Derek Martin
On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote:
 Derek Martin wrote:
  On Tue, Sep 02, 2008 at 10:55:54PM +, Marc 'BlackJack' Rintsch wrote:
  but the instances of `Popen` are no actions.  There's no way to
  execute a `Popen` instance.
 
  Yes there is... you execute it when you instantiate the object.  At
  the time of instantiation, you open the P (pipes).
 
 The subprocess module is also supposed to replace os.system and
 os.spawn*, neither of which involve opening pipes. 

Sigh... wasn't finished, sent by accident.  Anyway, to continue...

The subprocess module also can be used to replace these two functions,
though to be honest, it's not clear to me why one would do so.   On
the whole, I choose not to use the subprocess module because I find it
tedious, and less tedious interfaces (like os.system() and os.popen(),
and even the popen2 module) exist.  [But, you can probably guess that
I write code almost exclusively for POSIX-ish systems...]  If all you
want is the equivalent of os.system() or os.spawn(), then it seems to
me the subprocess module is overly heavy-handed, leaving a bunch of
not useful state laying around in your environment...  Not to mention
you probably already need the os module, so you could save yourself
the trouble and overhead of importing subprocess.

 All rationalizations aside, I think Popen is a poor name for the
 class.  

Even within this thread, a number of people clearly disagree with you. 
To say nothing of the maintainers... :)

I really think it's not worse (and actually better) than process...
for reasons I already explained.  The argument that the object is a
process is spurious.  The object is, in actuality, an instance of
*COMMUNICATION* between two processes.  It's true that a process is
started as a result, so that the first process has a second to be able
to communicate with; and a (tiny) bit of information (the PID) is
maintained about that process, mostly for no useful reason...  However
the object mainly is a collection of pipes, and some methods for
communicating over them, to another process that, out of necessity
just happens to be a child of the current one. 

If you think about what the methods do, and understand how they
actually work, I think it will become clear that this is the case.
Does communicate() operate on the process?  ABSOLUTELY NOT -- it
operates on the pipes.  poll() and wait() may arguably act upon the
process (they actually request information about the process from the
kernel), but the goal in doing so is to find out the status of the
communication: is it done, and if so was it successful?  If you
abstract the concept from its implementation, this is clearly true.  

I could concede that it may not be clear to someone unfamiliar with C
programming (perhaps especially in a Unix environment, though Windows
does have a similar, but apparently broken function) what popen
means or does, but the manual has ample references to explain that, I
think.  It's no less clear than the popen() function itself!

 But I would imagine the odds of it ever being changed are miniscule
 (Python 4?).

The truth is, in the end, I personally don't really care; though if it
were changed, I would hope something genuinely better were chosen.  I
feel strongly that process ain't it.  My motivation in posting in
this thread is mostly to point out how silly it is to argue or
complain about the name of some bit of logic in a programming
language, especially once it's already been released (though I doubt
most of the participants got the point).  The time to do this is when
the feature is in the planning stages, if ever...  Some people take
this stuff way, way too seriously, and also can't seem to imagine that
another perspective besides their own exists, and especially that
their own might just not be optimal/correct.  

Posting to Usenet/maling lists and saying Why is X called X?  It
should be called Y! is not likely to ever produce any sort of useful
result. ;-)

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgphiAy6Q03Hs.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote:

 And if they model an action there must be some way to activate the
 action
 
 That's a reasonable assumption, but as I also said, the object might
 just describe the action -- essentially the equivalent of a struct in C.

``struct``\s in C describe *actions*!?  Functions do this.  And a class 
that describes an action that is executed in the `__init__()` method is 
conceptually a function and shouldn't be a class.  There must be a better 
name for the thing it returns.  Again guideline, not law, but a very 
strong guideline IMHO.

 but the instances of `Popen` are no actions.  There's no way to
 execute a `Popen` instance.
 
 Yes there is... you execute it when you instantiate the object.

But then the instance itself isn't an action but the result of one.

 At the time of instantiation, you open the P (pipes).  For an
 object which describes an action, I think it's perfectly sensible that
 instantiation is when the action occurs, […]

Here I disagree again.  Because the type/class name of an instance should 
be a name of the thing/concept of the instance, not the action used to 
create it.

  Yet some of you state your case as if it is incontrovertable fact.
  I've given a good case as to why it IS a good name (one which I
  genuinely support), and disagree as you may, none of the points any
  of you have made invalidate or even weaken my argument.
 
 Maybe from your POV.  Facts:  It doesn't use the `popen()` function
 
 So?  Neither does the C version of popen(), but that function is still
 called popen()!

Now you lost me.  The C version of `popen()` isn't recursive, why on 
earth should it be, so what's that statement supposed to mean!?

 to three file objects, more attributes and methods), the function used
 on Windows under the hood is called `CreateProcess()` not
 `CreatePipe()`.
 
 How does Windows implement popen()?  [I think they call it _popen()
 though...]

Doesn't matter because the `Popen()` implementation doesn't use `popen()`.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list

Re: Pass same parameter in Recursive function

2008-09-03 Thread Diez B. Roggisch

Davy schrieb:

On Sep 3, 11:57 am, Chris Rebert [EMAIL PROTECTED] wrote:

Assuming the function is tail-recursive or the unchanging arguments
are immutable, just use a closure:

[SNIP]
Hi Chris,

Thank you :)
Perhaps I should clarify the problem.
1. the function is NOT tail-recursive
2. Yes, the arguments are immutable after I call the function the
first time.

I think the best description of the problem may be:
How to keep some argument constant and accessable in one function
(especially, recursive function). We know that we can use something
like self.parameter to keep the parameter constant and accessable in
one class.



The same way chris showed you - using a closure, you can capture 
variables outside, and only pass the changing params.


The tail-recursion property isn't needed for that.

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Derek Martin
On Wed, Sep 03, 2008 at 06:40:10AM +, Marc 'BlackJack' Rintsch wrote:
 On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote:
 
  And if they model an action there must be some way to activate the
  action
  
  That's a reasonable assumption, but as I also said, the object might
  just describe the action -- essentially the equivalent of a struct in C.
 
 ``struct``\s in C describe *actions*!?  Functions do this.  

struct run {
int speed;
direction_type direction;
};

Not a function.  Describes an action.  Sure, you'll probably never see
this example in a real program.  But that doesn't mean you can't do
it, and it doesn't make it inherently wrong.  Someone somewhere might
very well find a legitimate use case.

Besides which, I was not talking about programmatic actions; I was
talking about verbs -- actions that people do.

You are putting narrow-minded constraints on your ideas about how to
program.  Sometimes thinking outside the box is useful...

  but the instances of `Popen` are no actions.  There's no way to
  execute a `Popen` instance.
  
  Yes there is... you execute it when you instantiate the object.
 
 But then the instance itself isn't an action but the result of one.

So?  A class doesn't represent an action, remember?  It represents a
thing.  Isn't that what you said?

  At the time of instantiation, you open the P (pipes).  For an
  object which describes an action, I think it's perfectly sensible that
  instantiation is when the action occurs, […]
 
 Here I disagree again.  Because the type/class name of an instance should 
 be a name of the thing/concept of the instance, not the action used to 
 create it.

You're making an assertion based on your personal opinion.  That's a
fine guideline, but there's no requirement to do so.  I can name my
classes anything I want.  There's no reason I can't write:

Class Think:
def __init__:
self.thoughts = happy
print Thinking %s thoughts! %s self.thoughts 


This is a silly example that does nothing useful, but that doesn't
exclude the possibility that someone might conceive of a similar
example that is actually useful.  Maybe you're just not creative
enough, and I'm too lazy.

  Maybe from your POV.  Facts:  It doesn't use the `popen()` function
  
  So?  Neither does the C version of popen(), but that function is still
  called popen()!
 
 Now you lost me.  The C version of `popen()` isn't recursive, why on 
 earth should it be, so what's that statement supposed to mean!?

Sorry, did I go too fast for you?  Your facts  seem to be suggesting
that for Python's Popen class to be named Popen, it should use the C
popen() function.  I can't imagine any other reason why you mentioned
it doesn't...  It need not use popen() to do what popen() does...  In
fact, it need not do what popen() does to be called Popen!  It's just
a name... the author can call it whatever he wants.  As it happens, it
was called Popen because it does essentially what popen() does.  The
fact that it doesn't USE popen() to do it is... not interesting?

  to three file objects, more attributes and methods), the function used
  on Windows under the hood is called `CreateProcess()` not
  `CreatePipe()`.
  
  How does Windows implement popen()?  [I think they call it _popen()
  though...]
 
 Doesn't matter because the `Popen()` implementation doesn't use `popen()`.

No, that's exactly why it *does* matter.  Because neither is popen()
implemented using popen()!  See!  There you go again!

Does it matter, or doesn't it?!?  What are you trying to say?!?

Sorry, but you are contradicting yourself (repeatedly), and your
arguments don't make any sense.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpvhafSwjqFj.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Peter Otten
hofer wrote:

 Something I have to do very often is filtering / transforming line
 based file contents and storing the result in an array or a
 dictionary.
 
 Very often the functionallity exists already in form of a shell script
 with sed / awk / grep , . . .
 and I would like to have the same implementation in my script
 
 What's a compact, efficient (no intermediate arrays generated /
 regexps compiled only once) way in python
 for such kind of 'pipe line'
 
 Example 1 (in bash):  (annotated with comment (thus not working) if
 copied / pasted
 
 cat file \   ### read from file
 | sed 's/\.\..*//' \### remove '//' comments
 | sed 's/#.*//' \   ### remove '#' comments
 | grep -v '^\s*$'  \### get rid of empty lines
 | awk '{ print $1 + $2   $2 }' \ ### knowing, that all remaining
 lines contain always at least
 \   ### two integers calculate
 sum and 'keep' second number
 | grep '^42 ' ### keep lines for which sum is 42
 | awk '{ print $2 }' ### print number
 thanks in advance for any suggestions of how to code this (keeping the
 comments)

for line in open(file): # read from file
try:
a, b = map(int, line.split(None, 2)[:2]) # remove extra columns,
 # convert to integer
except ValueError:
pass # remove comments, get rid of empty lines,
 # skip lines with less than two integers
else:
# line did start with two integers
if a + b == 42: # keep lines for which the sum is 42
print b # print number

The hard part was keeping the comments ;)

Without them it looks better:

import sys
for line in sys.stdin:
try:
a, b = map(int, line.split(None, 2)[:2])
except ValueError:
pass
else:
if a + b == 42:
print b

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


Re: eval() == evil? --- How to use it safely?

2008-09-03 Thread mario
On Aug 28, 11:51 pm, Fett [EMAIL PROTECTED] wrote:
 I am creating a program that requires some data that must be kept up
 to date. What I plan is to put this data up on a web-site then have
 the program periodically pull the data off the web-site.

 My problem is that when I pull the data (currently stored as a
 dictionary on the site) off the site, it is a string, I can use eval()
 to make that string into a dictionary, and everything is great.
 However, this means that I am using eval() on some string on a web-
 site, which seems pretty un-safe.

 I read that by using eval(code,{__builtins__:None},{}) I can prevent
 them from using pretty much anything, and my nested dictionary of
 strings is still allowable. What I want to know is:

 What are the dangers of eval?
 - I originally was using exec() but switched to eval() because I
 didn't want some hacker to be able to delete/steal files off my
 clients computers. I assume this is not an issue with eval(), since
 eval wont execute commands.
 - What exactly can someone do by modifying my code string in a command
 like: thing = eval(code{__builtins__:None},{}), anything other than
 assign their own values to the object thing?

If you like to look at a specific attempt for making eval() safe(r)
take a look at how the **eval-based** Evoque Templating engine does
it, for which a short overview is here:
http://evoque.gizmojo.org/usage/restricted/

While it does not provide protection against DOS type attacks, it
should be safe against code that tries to pirate tangible resources
off your system, such as files and disk. Actually, any problems anyone
may find are greatly appreciated...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Gabriel Genellina
En Tue, 02 Sep 2008 19:15:07 -0300, Derek Martin [EMAIL PROTECTED]  
escribió:



 The Linux man page unfortunately copies (verbatim) the FreeBSD man
 page, which gets it wrong.  You can not open a process, but you can
 definitely open a pipe.

(Ok, if it doesn't agree with you, it must be wrong)


See my last post for accreditation of my comment.  A common
argumentation tactic of the closed-minded and the small-minded is to
resort to insinuation to attack the validity of other's comments
without providing any basis for doing so.  Nice job.


Well, you didn't provide (in that post) any reason for the Linux man page  
to be wrong, other than you disagreed with its terminology... But I don't  
want to argument on this - it was just a side note.



Classes represent things, and class names should be nouns.


Is that a law?

Classes are instantiated by invoking their class names as a function
call -- the computing equivalent of a verb.  Why then, must they be
named as nouns?  Can you not, in fact, have classes which describe
(or model) actions?  Wouldn't you name them using verbs if you did?


Not exactly. I usually use the -dor suffix (Spanish) or -er (English); in  
both languages their meaning is to make a noun from a verb. A class whose  
main purpose is to write things becomes a Writer, by example. The stdlib  
is full of Writers, Openers, Parsers, Wrappers, Handlers, etc. If the main  
purpose of subprocess.Popen were to open pipes, I'd say some form of  
opener would be OK. But I think its main purpose is to model the child  
process itself - pipes are just attributes, so a noun like Child,  
Subprocess, Process or similar would have been more adequate.
Of course it's too late to change things now, at least for the near  
future. Anyway, It's not the first misnamed class, nor the last one  
-unfortunately-, nor it's so badly named anyway...



That said, this is the most valid point anyone has made...  You should
have made it when the module was being designed. :-D


(Yes, sure. Unfortunately, by the time 2.4 was released, I was still stuck  
with Python 2.1 due to Zope incompatibilities... Properties and generators  
were unreachable things to me... Oh, just remembering those times makes me  
sick :( )



My point is, if you don't think Popen is a good name for the class,
that's your opinion, but it is only that: an opinion.  Yet some of you
state your case as if it is incontrovertable fact.  I've given a good
case as to why it IS a good name (one which I genuinely support), and
disagree as you may, none of the points any of you have made
invalidate or even weaken my argument.  Lastly, the maintainers
obviously thought it was a good name when they included it...


No, please. I know it's just my opinion, and I can see there is a case for  
the current name - just I don't like it, and liked to share my feelings  
with the OP when he said the same.


--
Gabriel Genellina

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


Problems with running Python CGI Scripts

2008-09-03 Thread Edward FISHER
Hey guys.
Im having problems running a python cgi. Im using the example code from:
http://www.python.org/doc/essays/pp...east/sld041.htm as writen by Van Rossum 
himself

I can get the script to run the python script but all that happens is that the 
black python box appears then disapears, the html that the python scripts 
should generate is never output.

My html is:

htmlhead
meta http-equiv=Content-Type content=text/html; charset=windows-1252
titleA Typical HTML form/title/head
body
p align=centerubfont size=5A Typical HTML form/font/b/u/p
p align=centerfont size=1 color=#FF*Test CGI script and HTML to
test server for correct running of python cgi scripting/font/p
form method='GET' action='http://www.fisherphotographics.co.uk/testcgia.pyc'
p align=centerYour First Name:
input type='text' name='firstname' size=20
p align=centerYour Last Name: input type='text' name='lastname' size=20
p align=centerClick here to submit form: input type='submit' value='Yeah!'
input type='hidden' name='session' value='1f9a2'
/form/body/html

This is calling the pyc file of the python script. I dont understand why if i 
call the py file itself all i get returned is the plain text of the python file.

The python script is:

#!/usr/local/bin/python
import cgi

def main():
print Content-type: text/html\n
form = cgi.FieldStorage()
if form.has_key(firstname) and form[firstname].value != :
#if form has an object called firstname and the value is not an empty string
print h1Hello, form[firstname].value, /h1
else:
print h1Error! Please enter first name./h1

main()

If you need to see what happens then follow this link:
http://www.fisherphotographics.co.uk/testhtml1.htm

The python file has come directly from the example so i must me doing something 
wrong. I have all the correct permissions etc
Thanks very much
Ed Fisher 
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write verbose scripts

2008-09-03 Thread Hendrik van Rooyen

Steven D'Aprano stev...bersource.com.au wrote:

Is there a better way of doing this than the way I am going about it?

Not sure if its better, but I would keep the messages in a table or dict and
have different tables or dicts for different levels of verbosity, and write a
displayer that knows about the verbosity - This approach has the advantage that
you can write in English and have different verbosities in different languages
too, if the displayer knows about the language.

Verbosity level and language can be display class attributes, and then you can
simply write something like:

display.display(squawk)

and get one of:

 squawk
 squawk, squawk, squawk
 squawk - help the bastards are trying to nail me to my perch!

or the equivalent in Icelandic or Norwegian.

It works, but its a PITA to implement because you have to formally construct the
stuff, and keep them all in sync, across languages and levels of verbosity.

This of course will only work for static messages - If you compute what you
display, I guess you need to either keep the computation in the displayer, or
pass it in, or something - gets messy.

Keeps the code clear though, as it splits what you display away from the
decision of saying something.

I try to avoid it if I can.

- Hendrik



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


Using httplib to access servlets on tomcat server

2008-09-03 Thread jorma kala
Hi,

I'm trying unsuccesfully to use the httplib library to execute servlets on a
local tomcat server.

If I type the following http adress on my browser
http://localhost:8080/test/Serv1  the servlet works fine.
But if I try to access it with the following python code:

   conn = httplib.HTTPConnection(http://localhost:8080;)
   conn.request(GET, /test/Serv1)
   r1 = conn.getresponse()

I get the following error:

socket.gaierror: (11001, 'getaddrinfo failed')

Do you know what I do wrong?
Thank you very much.


(The complete traceback is:

Traceback (most recent call last):
  File http1.py, line 130, in module
getTomcat1()
  File http1.py, line 46, in getTomcat1
conn.request(GET, /test/Serv1)
  File C:\Python25\lib\httplib.py, line 862, in request
self._send_request(method, url, body, headers)
  File C:\Python25\lib\httplib.py, line 885, in _send_request
self.endheaders()
  File C:\Python25\lib\httplib.py, line 856, in endheaders
self._send_output()
  File C:\Python25\lib\httplib.py, line 728, in _send_output
self.send(msg)
  File C:\Python25\lib\httplib.py, line 695, in send
self.connect()
  File C:\Python25\lib\httplib.py, line 663, in connect
socket.SOCK_STREAM):
socket.gaierror: (11001, 'getaddrinfo failed')
--
http://mail.python.org/mailman/listinfo/python-list

sys.stdin on windows

2008-09-03 Thread [EMAIL PROTECTED]
I often grep particular patterns out of large logfiles and then
pipeline the output to sort and uniq -c
I thought today to knock up a script to do the counting in a python
dict.

This seems work in linux

$ cat count.py
#!/usr/bin/env python
import sys
from collections import defaultdict
accumulator=defaultdict(int)
for line in sys.stdin.readlines():
accumulator[line.strip()]+=1
print contents,count
for key in accumulator.keys():
print key,,,accumulator[key]

$ cat test | ./count.py
contents,count
 , 1
23 , 1
1 , 1
3 , 2
2 , 2
5 , 3

When I try to run the same thing on windows I get
IOError: [Error 9] Bad file descriptor

How can I make this more windows friendly?

Thanks
Neil

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


Re: Using httplib to access servlets on tomcat server

2008-09-03 Thread Marco Bizzarri
On Wed, Sep 3, 2008 at 11:06 AM, jorma kala [EMAIL PROTECTED] wrote:
 Hi,

 I'm trying unsuccesfully to use the httplib library to execute servlets on a
 local tomcat server.

 If I type the following http adress on my browser
 http://localhost:8080/test/Serv1  the servlet works fine.
 But if I try to access it with the following python code:

conn = httplib.HTTPConnection(http://localhost:8080;)
conn.request(GET, /test/Serv1)
r1 = conn.getresponse()

 I get the following error:

 socket.gaierror: (11001, 'getaddrinfo failed')

 Do you know what I do wrong?
 Thank you very much.




localhost is not resolved to 127.0.0.1 on your machine.

Try changing it to http://127.0.0.1:8080

Regards
Marco


-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyparsing: match empty line

2008-09-03 Thread Marek Kubica
Hi,

First of all a big thank you for your excellent library and of course 
also for your extensive and enlightening answer!

 1) Well done in resetting the default whitespace characters, since you
 are doing some parsing that is dependent on the presence of line ends. 
 When you do this, it is useful to define an expression for end of line
 so that you can reference it where you explicitly expect to find line
 ends:
 
 EOL = LineEnd().suppress()

Ok, I didn't think about this. But as my program is not only a parser but 
a long-running process and setDefaultWhitespace modifies a global 
variable I don't feel too comfortable with it. I could set the whitespace 
on every element, but that is as you surely agree quite ugly. Do you 
accept patches? I'm thinking about some kind of factory-class which would 
automatically set the whitespaces:

 factory = TokenFactory(' \t\r')
 word = Factory.Word(alphas)


That way, one wouldn't need to set a grobal value which might interfere 
with other pyparsers running in the same process.

 parser = OneOrMore(watchname ^ pagebreak ^ leaveempty ^ EOL)
 
 This will now permit the second test to pass.

Right. Seems that working with whitespace requires a bit better 
understanding than I had.

 3) Your definition of pagebreak looks okay now, but I don't understand
 why your test containing 2 blank lines is only supposed to generate a
 single PAGEBREAK.

No, it should be one PAGEBREAK per blank line, now it works as expected.

 4) leaveempty probably needs this parse action to be attached to it:
 
 leaveempty =
 Literal('EMPTY').setParseAction(replaceWith('EMPTY'))

I added this in the meantime. replaceWith is really a handy helper.

 parser = OneOrMore(watchname | pagebreak | leaveempty | EOL)
 
 '|' operators generate MatchFirst expressions.  MatchFirst will do
 short-circuit evaluation - the first expression that matches will be the
 one chosen as the matching alternative.

Okay, adjusted it.

 If you have more pyparsing questions, you can also post them on the
 pyparsing wiki - the Discussion tab on the wiki Home page has become a
 running support forum - and there is also a Help/Discussion mailing
 list.

Which of these two would you prefer?

Thanks again, it works now just as I imagined!

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


installing matplotlib with cygwiin

2008-09-03 Thread Anish Chapagain
Hi!!
I need to run matplotlib for one project with pylab and scipy module,
i'm using cygwin so as to link system call operation with few GUI
support,
but am unable to install numpy and scipy without these matplotlib is
also not installed

Please help me for proper installation of these module in cygwin for
python, i followed scipy.org installation guidelines but having done
so, am not able to proper installation.

regard's
anish
--
http://mail.python.org/mailman/listinfo/python-list


Serial I/O problem with pywin32 ?

2008-09-03 Thread Xavier
Hi,

I try to access to a Bluetooth GPS data-logger with Python. I use
pySerial.

Sending and receiving little messages (~100 char) works fine. However,
when I ask the GPS to dump the trails, it returns some Mbytes and here
is the problem : in the stream of bytes, I randomly losts chunks of
~100bytes.

I tried USPP and pyBlueZ instead of pySerial : same problem.

It doesn't like it is a bufferoverun bug from me because :
 - the GPS seems to wait when I do not read the stream,
 - there is never more than 200 inWainting() characters,
 - my code to test it is quite simple :

  seriallink = serial.Serial(COM40)
  fileName = data.dump
  out = open(fileName, 'w')
  while 1:
c = seriallink.read()
out.write( %0.2X % ord(c))
print *,
  out.close()

(with pyBluez :
sock=BluetoothSocket( RFCOMM )
sock.connect((00:0A:..., 1)))

I tried my program on two different PC with two Bluetooth dongle,
(with pySerial, USPP, pyBluez).
The same things are :
 - windows
 - the GPS (which works fine with the dumper program of the
constructor)
 - pyWin32

I've found another guy with a similar problem :
http://www.generation-nt.com/reponses/rs232-entraide-142097.html
He says:
 - no problem with little messages
 - lost of one byte every hour when receiving a lot of data

Any known problems with pywin32 and serial I/O when downloading a big
stream of data ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with running Python CGI Scripts

2008-09-03 Thread Gabriel Genellina
En Wed, 03 Sep 2008 05:29:39 -0300, Edward FISHER [EMAIL PROTECTED]  
escribi�:


I can get the script to run the python script but all that happens is  
that the black python box appears then disapears, the html that the  
python scripts should generate is never output.

[...]
This is calling the pyc file of the python script. I dont understand why  
if i call the py file itself all i get returned is the plain text of the  
python file.


That's a server setting (Apache or whatever) - make sure it is configured  
to *execute* the script.



The python script is:

#!/usr/local/bin/python
import cgi

def main():
print Content-type: text/html\n


I hope this is just the way you posted your message, but remember that in  
Python indentation is important. The above code isn't valid. Once you are  
sure that your script doesn't have syntax errors, add this lines on the  
top to help debugging:


import cgitb; cgitb.enable()

--
Gabriel Genellina

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

installing matplotlib with numpy and scipy for Python in Cygwin

2008-09-03 Thread chapagainanish
Hi!!
I'm having installation problem for installing numpy and scipy in 
Cygwin for Python, and am obstruct in madway for project, i followed 
scipy.org guidelines but there's few error thrown as 
failed..with exit status 1

please if someone has installed these module help me
thank's and regard's
Anish


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


Re: python - mechanize/browser/POST issue

2008-09-03 Thread Mohamed Yousef
Hello ,

i don't know about mechanize but in general all you have to do is a
simple socket text sending
connect to the server then send it POST headers to page in question..

what to send ? getting this your self is much better and one of the
best tools is LiveHTTPHeaders - an addon for firefox -
so open it post the form in browser then see what you got in
LiveHttpHeaders , it will also help you more read through the form
being posted html code (knowing posted fields)

Regards,
Mohamed Yousef

2008/9/3 bruce [EMAIL PROTECTED]:
 evening...

 using mechanize/Browser, i can easily do a url/get, and process submitting a
 form that uses a GET as the action. however, I'm not quite sure how to
 implement the submittal of a form, that uses the POST action.

 Anyone have a short chunk of code that I can observer, that uses the
 mechanize.Browser implentation?

 in searching the net, i haven't found any...

 thanks


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

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


Re: sys.stdin on windows

2008-09-03 Thread Gabriel Genellina
En Wed, 03 Sep 2008 06:16:03 -0300, [EMAIL PROTECTED] [EMAIL PROTECTED]  
escribi�:



I often grep particular patterns out of large logfiles and then
pipeline the output to sort and uniq -c
I thought today to knock up a script to do the counting in a python
dict.

This seems work in linux

$ cat count.py
#!/usr/bin/env python
import sys
from collections import defaultdict
accumulator=defaultdict(int)
for line in sys.stdin.readlines():
accumulator[line.strip()]+=1
print contents,count
for key in accumulator.keys():
print key,,,accumulator[key]

$ cat test | ./count.py
contents,count
 , 1
23 , 1
1 , 1
3 , 2
2 , 2
5 , 3

When I try to run the same thing on windows I get
IOError: [Error 9] Bad file descriptor

How can I make this more windows friendly?


Explicitely invoking the interpreter worked for me. That is, these two  
commands worked fine:


type test.txt | python count.py
python count.py  test.txt

But I cannot explain *why* it doesn't work the other way.

--
Gabriel Genellina

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

Re: eval() == evil? --- How to use it safely?

2008-09-03 Thread rustom
On Aug 29, 4:42 am, castironpi [EMAIL PROTECTED] wrote:

 May I suggest PyYAML?

I second that.

Yaml is very pythonic (being indentation based) and pyyaml is sweet.

Only make sure you use safe_load not load and you will have only
default construction for standard python objects -- lists,
dictionaries and 'atomic' things so no arbitrary code can be executed.

Someone else suggested json which is about the same as yml if there
are no objects. And by using safe_load you are not using objects.
--
http://mail.python.org/mailman/listinfo/python-list


Re: sys.stdin on windows

2008-09-03 Thread Tim Golden

Gabriel Genellina wrote:
En Wed, 03 Sep 2008 06:16:03 -0300, [EMAIL PROTECTED] 
[EMAIL PROTECTED] escribi�:



I often grep particular patterns out of large logfiles and then
pipeline the output to sort and uniq -c
I thought today to knock up a script to do the counting in a python
dict.

This seems work in linux

$ cat count.py
#!/usr/bin/env python
import sys
from collections import defaultdict
accumulator=defaultdict(int)
for line in sys.stdin.readlines():
accumulator[line.strip()]+=1
print contents,count
for key in accumulator.keys():
print key,,,accumulator[key]

$ cat test | ./count.py
contents,count
 , 1
23 , 1
1 , 1
3 , 2
2 , 2
5 , 3

When I try to run the same thing on windows I get
IOError: [Error 9] Bad file descriptor

How can I make this more windows friendly?


Explicitely invoking the interpreter worked for me. That is, these two 
commands worked fine:


type test.txt | python count.py
python count.py  test.txt

But I cannot explain *why* it doesn't work the other way.



Known bug in NT-based file association. I'll try 
to find an online reference, but that's basically

what it comes to. I think you can faff-about with
batch files to achieve the effect, but I can't
quite remember.

http://support.microsoft.com/kb/321788

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

Re: sys.stdin on windows

2008-09-03 Thread [EMAIL PROTECTED]
On Sep 3, 11:16 pm, Tim Golden [EMAIL PROTECTED] wrote:
 Gabriel Genellina wrote:
  En Wed, 03 Sep 2008 06:16:03 -0300, [EMAIL PROTECTED]
  [EMAIL PROTECTED] escribi :

  I often grep particular patterns out of large logfiles and then
  pipeline the output to sort and uniq -c
  I thought today to knock up a script to do the counting in a python
  dict.

  This seems work in linux

  $ cat count.py
  #!/usr/bin/env python
  import sys
  from collections import defaultdict
  accumulator=defaultdict(int)
  for line in sys.stdin.readlines():
      accumulator[line.strip()]+=1
  print contents,count
  for key in accumulator.keys():
      print key,,,accumulator[key]

  $ cat test | ./count.py
  contents,count
   , 1
  23 , 1
  1 , 1
  3 , 2
  2 , 2
  5 , 3

  When I try to run the same thing on windows I get
  IOError: [Error 9] Bad file descriptor

  How can I make this more windows friendly?

  Explicitely invoking the interpreter worked for me. That is, these two
  commands worked fine:

  type test.txt | python count.py
  python count.py  test.txt

  But I cannot explain *why* it doesn't work the other way.

 Known bug in NT-based file association. I'll try
 to find an online reference, but that's basically
 what it comes to. I think you can faff-about with
 batch files to achieve the effect, but I can't
 quite remember.

 http://support.microsoft.com/kb/321788

 TJG

Thanks.

I'll ues the explicit python call.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Renumbering

2008-09-03 Thread Philipp Pagel
Francesco Pietra [EMAIL PROTECTED] wrote:
 ATOM   3424  N   LEU B 428 143.814  87.271  77.726  1.00115.20   
 2SG3426
 ATOM   3425  CA  LEU B 428 142.918  87.524  78.875  1.00115.20   
 2SG3427
[...]

 As you can see, the number of lines for a particular value in column 6
 changes from situation to situation, and may even be different for the
 same name in column 4. For example, LEU can have a different number of
 lines depending on the position of this amino acid (leucine).

Others have alreade given good hints but I would like to add a bit of
advice. 

The data you show appears to be a PDB protein structure file. It is
important to realize that these are fixed-width files and columns can be
empty so splitting on tab or whithespace will often fail. It is also
important to know that the residue numbering (cols 23-26) is not
necessarily contiguous and is not even unique without taking into
account the 'insertion code' in column 27 which happens to be empty in
your example. I would recommend to use a full-blown PDB parser to read
the data and then iterate over the residues and do whatever you would
like to acomplish that way. Biopython has such a parser:

www.biopython.org

cu
Philipp

-- 
Dr. Philipp Pagel
Lehrstuhl f. Genomorientierte Bioinformatik
Technische Universität München
http://mips.gsf.de/staff/pagel
--
http://mail.python.org/mailman/listinfo/python-list


Re: python - mechanize/browser/POST issue

2008-09-03 Thread Wojtek Walczak
On Tue, 2 Sep 2008 19:39:05 -0700, bruce wrote:

 using mechanize/Browser, i can easily do a url/get, and process submitting a
 form that uses a GET as the action. however, I'm not quite sure how to
 implement the submittal of a form, that uses the POST action.

 Anyone have a short chunk of code that I can observer, that uses the
 mechanize.Browser implentation?

Take a look at the bottom of this post:

http://mail.python.org/pipermail/python-list/2006-June/390037.html

It seems that submit does the job.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write verbose scripts

2008-09-03 Thread Bruno Desthuilliers

John Machin a écrit :

On Sep 3, 3:52 am, Mensanator [EMAIL PROTECTED] wrote:

On Sep 2, 11:55 am, Steven D'Aprano [EMAIL PROTECTED]

  if (p  1)==1:
print_evens = True
  else:
print_evens = False
  if (p  2)==2:
print_odds = True
  else:
print_odds = False
  if (p  4)==4:
print_debug = True
  else:
print_debug = False


No, no, no, you've taken How to write verbose scripts rather too
literally; 


KEYBOARD !

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


Re: How to write verbose scripts

2008-09-03 Thread Uwe Schmitt
On 2 Sep., 18:55, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 I find myself writing command line tools in Python where I wish to
 include verbose output to stdout.

 I start with a helper function:

 def print_(obj, level=0):
     if _verbosity = level:
         print obj

 And then I end up with functions or methods looking like this:

 def parrot(x)
     print_(precondition, level=2)
     do_something()
     print_(status is good..., level=1)
     print_(parrot is squawking strongly now, level=2)
     do_something_else()
     print_(squawk squawk squawk, level=3)
     do_more()
     print_(postcondition, level=1)
     return something

 That often means that my functions end up with more message printing code
 than actual code. The whole thing seems messy and hard to manage for all
 but the smallest scripts.

 Worst of all, sometimes the messages I wish to print may be expensive to
 compute, and I don't want to waste time computing them if they aren't
 going to be printed because the verbosity is too low. But nor do I wish
 to fill my code with this:

 if _verbosity = 3:
     x = calculate_complicated_thing()
     print_(x, level=3)

 Is there a better way of doing this than the way I am going about it?

 --
 Steven

You can save some code if you use function decorators for logging
input and output values of
functions.
So write lots of functions containing one statement and your problem
is solved ;-)

Greetings, Uwe

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


Re: installing matplotlib with numpy and scipy for Python in Cygwin

2008-09-03 Thread Uwe Schmitt
On 3 Sep., 11:42, chapagainanish [EMAIL PROTECTED] wrote:
 Hi!!
 I'm having installation problem for installing numpy and scipy in
 Cygwin for Python, and am obstruct in madway for project, i followed
 scipy.org guidelines but there's few error thrown as
         failed..with exit status 1

 please if someone has installed these module help me
 thank's and regard's
 Anish

http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html
may help you.

Do you really want a cygwin based installation ?
You could download enthoughts python edition which
includes lots of math stuff.

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


Re: installing matplotlib with numpy and scipy for Python in Cygwin

2008-09-03 Thread Anish Chapagain
On Sep 3, 12:39 pm, Uwe Schmitt [EMAIL PROTECTED]
wrote:
 On 3 Sep., 11:42, chapagainanish [EMAIL PROTECTED] wrote:

  Hi!!
  I'm having installation problem for installing numpy and scipy in
  Cygwin for Python, and am obstruct in madway for project, i followed
  scipy.org guidelines but there's few error thrown as
          failed..with exit status 1

  please if someone has installed these module help me
  thank's and regard's
  Anish

 http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html
 may help you.

 Do you really want a cygwin based installation ?
 You could download enthoughts python edition which
 includes lots of math stuff.

 Greetings, Uwe

Hi,
thank's i'm looking through the link cens.ioc.ee
and am in need of using matplotlib and to run few system call, so i
installed cygwin baically for system call in linux/unix and matplotlib
for GUI(graph,chart) but matplotlib is not getting installed in
cygwin..

any further help will be heartly accepted

thank's
anish
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDEs with F5 or hotkey shell interaction

2008-09-03 Thread Marco Bizzarri
On Tue, Sep 2, 2008 at 4:01 PM, mmm [EMAIL PROTECTED] wrote:

 I might look at
  Eclypse with pydev
  Jedit
 And these commercial/professional IDEs
  Wing
  Komodo IDE
  Zeus

 But before doing so I wanted to know form experienced users:

 ** How hard is it to configure any of the general editors/IDEs to run
 a Python shell using a hotkey (such as IDLEs F5) and whether any can
 be set up for full interactivity.

 I understand and appreciate  the difficulties to get full IDLE-like
 interactivity, but what comes closest?
 --
 http://mail.python.org/mailman/listinfo/python-list


I do not think I qualify for experienced users; I've used pydev for
many years, and I'm quite comfortable with it. It is an eclipse based
IDE, therefore you've some of its niceties and some of its drawbacks.

Regards
Marco

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

 Without them it looks better:
 
 import sys
 for line in sys.stdin:
 try:
 a, b = map(int, line.split(None, 2)[:2])
 except ValueError:
 pass
 else:
 if a + b == 42:
 print b

I'm philosophically opposed to one-liners like:

 a, b = map(int, line.split(None, 2)[:2])

because they're difficult to understand at a glance.  You need to visually 
parse it and work your way out from the inside to figure out what's going 
on.  Better to keep it longer and simpler.

Now that I've got my head around it, I realized there's no reason to make 
the split part so complicated.  No reason to limit how many splits get done 
if you're explicitly going to slice the first two.  And since you don't 
need to supply the second argument, the first one can be defaulted as well.  
So, you immediately get down to:

 a, b = map(int, line.split()[:2])

which isn't too bad.  I might take it one step further, however, and do:

 fields = line.split()[:2]
 a, b = map(int, fields)

in fact, I might even get rid of the very generic, but conceptually 
overkill, use of map() and just write:

 a, b = line.split()[:2]
 a = int(a)
 b = int(b)
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Peter Otten
Roy Smith wrote:

 In article [EMAIL PROTECTED],
  Peter Otten [EMAIL PROTECTED] wrote:
 
 Without them it looks better:
 
 import sys
 for line in sys.stdin:
 try:
 a, b = map(int, line.split(None, 2)[:2])
 except ValueError:
 pass
 else:
 if a + b == 42:
 print b
 
 I'm philosophically opposed to one-liners 

I'm not, as long as you don't /force/ the code into one line.

 like: 
 
 a, b = map(int, line.split(None, 2)[:2])
 
 because they're difficult to understand at a glance.  You need to visually
 parse it and work your way out from the inside to figure out what's going
 on.  Better to keep it longer and simpler.
 
 Now that I've got my head around it, I realized there's no reason to make
 the split part so complicated.  No reason to limit how many splits get
 done
 if you're explicitly going to slice the first two.  And since you don't
 need to supply the second argument, the first one can be defaulted as
 well. So, you immediately get down to:
 
 a, b = map(int, line.split()[:2])

I agree that the above is an improvement.
 
 which isn't too bad.  I might take it one step further, however, and do:
 
 fields = line.split()[:2]
 a, b = map(int, fields)
 
 in fact, I might even get rid of the very generic, but conceptually
 overkill, use of map() and just write:
 
 a, b = line.split()[:2]
 a = int(a)
 b = int(b)

If you go that route your next step is to introduce another try...except,
one for the unpacking and another for the integer conversion...

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


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread bearophileHUGS
Roy Smith:
 No reason to limit how many splits get done if you're
 explicitly going to slice the first two.

You are probably right for this problem, because most lines are 2
items long, but in scripts that have to process lines potentially
composed of many parts, setting a max number of parts speeds up your
script and reduces memory used, because you have less parts at the
end.

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


new python docs

2008-09-03 Thread Rick Dooling
Wow!  I've been away in other pursuits.

The new docs are gorgeous and searchable.

http://docs.python.org/dev/index.html

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


max(), sum(), next()

2008-09-03 Thread bearophileHUGS
Empty Python lists [] don't know the type of the items it will
contain, so this sounds strange:

 sum([])
0

Because that [] may be an empty sequence of someobject:

 sum(s for s in [a, b] if len(s)  2)
0

In a statically typed language in that situation you may answer the
initializer value of the type of the items of the list, as I do in the
sum() in D.

This sounds like a more correct/clean thing to do:

 max([])
Traceback (most recent call last):
  File stdin, line 1, in module
ValueError: max() arg is an empty sequence

So it may be better to make the sum([]) too raise a ValueError, in
Python 3/3.1 (if this isn't already true). On the other hand often
enough I have code like this:

 max(fun(x) for x in iterable if predicate(x))

This may raise the ValueError both if iterable is empty of if the
predicate on its items is always false, so instead of catching
exceptions, that I try to avoid, I usually end with a normal loop,
that's readable and fast:

max_value = smallvalue
for x in iterable:
if predicate(x):
max_value = max(max_value, fun(x))

Where running speed matters, I may even replace that max(max_value,
fun(x)) with a more normal if/else.

A possible alternative is to add a default to max(), like the next()
built-in of Python 2.6:

 max((fun(x) for x in iterable if predicate(x)), default=smallvalue)

This returns smallvalue if there are no items to compute the max of.

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


Re: How to write verbose scripts

2008-09-03 Thread BJörn Lindqvist
2008/9/3 Hendrik van Rooyen [EMAIL PROTECTED]:

 Steven D'Aprano stev...bersource.com.au wrote:

Is there a better way of doing this than the way I am going about it?

 Not sure if its better, but I would keep the messages in a table or dict and
 have different tables or dicts for different levels of verbosity, and write a
 displayer that knows about the verbosity - This approach has the advantage 
 that
 you can write in English and have different verbosities in different languages
 too, if the displayer knows about the language.

One big downside with that approach is that it becomes much harder to
grep for the log message. Usually when I go through logs, I don't care
what exactly the message says, just that it is easily googleable (uses
some kind of identifying text) and that it is unique so I can know
exactly where it was emitted.


-- 
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


Custom handler for logging

2008-09-03 Thread Luigi Paioro

Dear all,

concerning the logging module, I have written a new Handler which stores 
the logging messages in an SQLite database. It works well, but when I 
try to use it exploiting a configuration file I have a problem since the 
class entry does not accept a class which is not within the logging 
name-space, while the class I implemented is coded in my personal module 
(thus another name-space).


Is there a workaround to allow the usage of custom handlers?

Thanks in advance.

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


Re: pyparsing: match empty line

2008-09-03 Thread Paul McGuire
On Sep 3, 4:26 am, Marek Kubica [EMAIL PROTECTED] wrote:
 Hi,

 First of all a big thank you for your excellent library and of course
 also for your extensive and enlightening answer!


I'm glad pyparsing has been of help to you.  Pyparsing is building its
own momentum these days.  I have a new release in SVN that I'll put
out in the next week or so.


 Ok, I didn't think about this. But as my program is not only a parser but
 a long-running process and setDefaultWhitespace modifies a global
 variable I don't feel too comfortable with it.

Pyparsing isn't really all that thread-friendly.  You definitely
should not have multiple threads using the same grammar.  The
approaches I've seen people use in multithread applications are: 1)
synchronize access to a single parser across multiple threads, and 2)
create a parser per-thread, or use a pool of parsers.  Pyparsing
parsers can be pickled, so a quick way to reconstitute a parser is to
create the parser at startup time and pickle it to a string, then
unpickle a new parser as needed.


 I could set the whitespace
 on every element, but that is as you surely agree quite ugly. Do you
 accept patches? I'm thinking about some kind of factory-class which would
 automatically set the whitespaces:

  factory = TokenFactory(' \t\r')
  word = Factory.Word(alphas)

 That way, one wouldn't need to set a grobal value which might interfere
 with other pyparsers running in the same process.

I tried to prototype up your TokenFactory class, but once I got as far
as implementing __getattribute__ to return the corresponding pyparsing
class, I couldn't see how to grab the object generated for that class,
and modify its whitespace values.  I did cook up this, though:

class SetWhitespace(object):
def __init__(self, whitespacechars):
self.whitespacechars = whitespacechars

def __call__(self,pyparsing_expr):
pyparsing_expr.setWhitespace(self.whitespacechars)
return pyparsing_expr

noNLskipping = SetWhitespace(' \t\r')
word = noNLskipping(Word(alphas))

I'll post this on the wiki and see what kind of comments we get.

By the way, setDefaultWhitespace only updates global variables that
are used at parser definition time, *not* at parser parse time.  So,
again, you can manage this class attribute at the initialization of
your program, before any incoming requests need to make use of one
parser or another.


  4) leaveempty probably needs this parse action to be attached to it:

  leaveempty =
  Literal('EMPTY').setParseAction(replaceWith('EMPTY'))

 I added this in the meantime. replaceWith is really a handy helper.

After I released replaceWith, I received a parser from someone who
hadn't read down to the 'R's yet in the documentation, and he
implemented the same thing with this simple format:

 leaveempty = Literal('EMPTY').setParseAction(lambda : 'EMPTY')

These are pretty much equivalent, I was just struck at how easy Python
makes things for us, too!


  If you have more pyparsing questions, you can also post them on the
  pyparsing wiki - the Discussion tab on the wiki Home page has become a
  running support forum - and there is also a Help/Discussion mailing
  list.

 Which of these two would you prefer?


They are equivalent, I monitor them both, and you can browse through
previous discussions using the Discussion tab online threads, or the
mailing list archive on SF.  Use whichever is easier for you to work
with.

Cheers, and Welcome to Pyparsing!
-- Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Custom handler for logging

2008-09-03 Thread Peter Otten
Luigi Paioro wrote:

 concerning the logging module, I have written a new Handler which stores
 the logging messages in an SQLite database. It works well, but when I
 try to use it exploiting a configuration file I have a problem since the
 class entry does not accept a class which is not within the logging
 name-space, while the class I implemented is coded in my personal module
 (thus another name-space).
 
 Is there a workaround to allow the usage of custom handlers?

Maybe

http://mail.python.org/pipermail/python-list/2003-October/232762.html

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


Re: new python docs

2008-09-03 Thread Colin J. Williams

Rick Dooling wrote:

Wow!  I've been away in other pursuits.

The new docs are gorgeous and searchable.

http://docs.python.org/dev/index.html

Thank you, python.org.


Yes, they look crisp and clear. It would 
have been nice if the Apple folk, in 
their clear Style Guide, had provided 
hyperlinks to the various documents 
referenced.


Thanks to all the pythoneers who 
contributed to the documentation.


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


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

  I might take it one step further, however, and do:
  
  fields = line.split()[:2]
  a, b = map(int, fields)
  
  in fact, I might even get rid of the very generic, but conceptually
  overkill, use of map() and just write:
  
  a, b = line.split()[:2]
  a = int(a)
  b = int(b)
 
 If you go that route your next step is to introduce another try...except,
 one for the unpacking and another for the integer conversion...

Why another try/except?  The potential unpack and conversion errors exist 
in both versions, and the existing try block catches them all.  Splitting 
the one line up into three with some intermediate variables doesn't change 
that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Roy Smith:
  No reason to limit how many splits get done if you're
  explicitly going to slice the first two.
 
 You are probably right for this problem, because most lines are 2
 items long, but in scripts that have to process lines potentially
 composed of many parts, setting a max number of parts speeds up your
 script and reduces memory used, because you have less parts at the
 end.
 
 Bye,
 bearophile

Sounds like premature optimization to me.  Make it work and be easy to 
understand first.  Then worry about how fast it is.

But, along those lines, I've often thought that split() needed a way to not 
just limit the number of splits, but to also throw away the extra stuff.  
Getting the first N fields of a string is something I've done often enough 
that refactoring the slicing operation right into the split() code seems 
worthwhile.  And, it would be even faster :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Custom handler for logging

2008-09-03 Thread Luigi Paioro

Thanks, it works perfectly!

Luigi

Peter Otten ha scritto:

Luigi Paioro wrote:


concerning the logging module, I have written a new Handler which stores
the logging messages in an SQLite database. It works well, but when I
try to use it exploiting a configuration file I have a problem since the
class entry does not accept a class which is not within the logging
name-space, while the class I implemented is coded in my personal module
(thus another name-space).

Is there a workaround to allow the usage of custom handlers?


Maybe

http://mail.python.org/pipermail/python-list/2003-October/232762.html

Peter

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


properties setting each other

2008-09-03 Thread mk

Hello everyone,

I try to set two properties, value and square in the following code, 
and arrange it in such way that setting one property also sets another 
one and vice versa. But the code seems to get Python into infinite loop:


 import math
 class Squared2(object):

def __init__(self, val):
self._internalval=val
self.square=pow(self._internalval,2)

def fgetvalue(self):
return self._internalval

def fsetvalue(self, val):
self._internalval=val
self.square=pow(self._internalval,2)

value = property(fgetvalue, fsetvalue)

def fgetsquare(self):
return self.square
def fsetsquare(self,s):
self.square = s
self.value = math.sqrt(self.square)

square = property(fgetsquare, fsetsquare)


 a=Squared2(5)

Traceback (most recent call last):
  File pyshell#11, line 1, in module
a=Squared2(5)
  File pyshell#10, line 5, in __init__
self.square=pow(self._internalval,2)
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare

...

Is there a way to achieve this goal of two mutually setting properties?

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


Re: installing matplotlib with numpy and scipy for Python in Cygwin

2008-09-03 Thread Diez B. Roggisch

Anish Chapagain schrieb:

On Sep 3, 12:39 pm, Uwe Schmitt [EMAIL PROTECTED]
wrote:

On 3 Sep., 11:42, chapagainanish [EMAIL PROTECTED] wrote:


Hi!!
I'm having installation problem for installing numpy and scipy in
Cygwin for Python, and am obstruct in madway for project, i followed
scipy.org guidelines but there's few error thrown as
failed..with exit status 1
please if someone has installed these module help me
thank's and regard's
Anish

http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html
may help you.

Do you really want a cygwin based installation ?
You could download enthoughts python edition which
includes lots of math stuff.

Greetings, Uwe


Hi,
thank's i'm looking through the link cens.ioc.ee
and am in need of using matplotlib and to run few system call, so i
installed cygwin baically for system call in linux/unix and matplotlib
for GUI(graph,chart) but matplotlib is not getting installed in
cygwin..


What are system calls? You *have* windows, so in the end you can do 
everything with normal python. And I presume that your codebase is by 
far smaller that matplotlibs, so adapting your source is easier than 
theirs.


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


Re: pyparsing: match empty line

2008-09-03 Thread Marek Kubica
On Wed, 03 Sep 2008 06:12:47 -0700, Paul McGuire wrote:

 On Sep 3, 4:26 am, Marek Kubica [EMAIL PROTECTED] wrote:

 I could set the whitespace
 on every element, but that is as you surely agree quite ugly. Do you
 accept patches? I'm thinking about some kind of factory-class which
 would automatically set the whitespaces:

  factory = TokenFactory(' \t\r')
  word = Factory.Word(alphas)

 That way, one wouldn't need to set a grobal value which might interfere
 with other pyparsers running in the same process.
 
 I tried to prototype up your TokenFactory class, but once I got as far
 as implementing __getattribute__ to return the corresponding pyparsing
 class, I couldn't see how to grab the object generated for that class,
 and modify its whitespace values.

I have had the same problem, until I remembered that I can fake __init__ 
using a function closure.

I have imported pyparsing.py into a hg repository with a patchstack, here 
is my first patch:

diff -r 12e2bbff259e pyparsing.py
--- a/pyparsing.py  Wed Sep 03 09:40:09 2008 +
+++ b/pyparsing.py  Wed Sep 03 14:08:15 2008 +
@@ -1400,9 +1400,38 @@
 def __req__(self,other):
 return self == other
 
+class TokenFinder(type):
+Collects all classes that are derived from Token
+token_classes = dict()
+def __init__(cls, name, bases, dict):
+# save the class
+TokenFinder.token_classes[cls.__name__] = cls
+
+class WhitespaceTokenFactory(object):
+def __init__(self, whitespace):
+self._whitespace = whitespace
+
+def __getattr__(self, name):
+Get an attribute of this class
+# check whether there is such a Token
+if name in TokenFinder.token_classes:
+token = TokenFinder.token_classes[name]
+# construct a closure which fakes the constructor
+def _callable(*args, **kwargs):
+obj = token(*args, **kwargs)
+# set the whitespace on the token
+obj.setWhitespaceChars(self._whitespace)
+return obj
+# return the function which returns an instance of the Token
+return _callable
+else:
+raise AttributeError('%s' object has no attribute '%s' % (
+WhitespaceTokenFactory.__name__, name))
 
 class Token(ParserElement):
 Abstract ParserElement subclass, for defining atomic matching 
patterns.
+__metaclass__ = TokenFinder
+
 def __init__( self ):

I used metaclasses for getting all Token-subclasses so new classes that 
are created are automatically accessible via the factory, without any 
additional registration.

Oh and yes, more patches will follow. I'm currently editing the second 
patch, but I better mail it directly to you as it is not really 
interesting for this list.

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


Re: max(), sum(), next()

2008-09-03 Thread Sion Arrowsmith
 [EMAIL PROTECTED] wrote:
Empty Python lists [] don't know the type of the items it will
contain, so this sounds strange:

 sum([])
0

 help(sum)
sum(...)
sum(sequence, start=0) - value

 sum(range(x) for x in range(5))
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: unsupported operand type(s) for +: 'int' and 'list'
 sum((range(x) for x in range(5)), [])
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

... so the list might not know what type it contains, but sum
does. And if you don't tell it, it makes a sensible guess. And
it *is* a case where refusing the temptation to guess is the
wrong thing: how many times would you use sum to do anything
other than sum numeric values? And how tedious would it be to
have to write sum(..., 0) for every other case? Particularly
bearing in mind:

 sum([a, b], )
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: sum() can't sum strings [use ''.join(seq) instead]

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   Frankly I have no feelings towards penguins one way or the other
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list

Re: Numeric literal syntax

2008-09-03 Thread Grant Edwards
On 2008-09-02, Christian Heimes [EMAIL PROTECTED] wrote:
 Fredrik Lundh wrote:
 Peter Pearson wrote:
 
 (startled noises) It is a delight to find a reference to
 that half-century-old essay (High Finance) by the wonderful
 C. Northcote Parkinson, but how many readers will catch the
 allusion?
 
 anyone that's been involved in open source on the development side for 
 more than, say, ten minutes.

 Indeed! Thus speaks the experienced developer -- effbot :)

 On some mailing lists the bikeshed issue comes hand in hand with the 
 Dunning-Kruger-effect. [1] *sigh*

 Christian

 [1] http://en.wikipedia.org/wiki/Dunning-Kruger_effect

That paper is really very interesting -- it explains a lot of
what one sees in corporate life.

-- 
Grant Edwards   grante Yow! I just remembered
  at   something about a TOAD!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-03 Thread Grant Edwards
On 2008-09-03, Ben Finney [EMAIL PROTECTED] wrote:
 Ben Finney [EMAIL PROTECTED] writes:

 I don't see any good reason (other than your familiarity with the D
 language) to use underscores for this purpose, and much more reason
 (readability, consistency, fewer arbitrary differences in syntax,
 perhaps simpler implementation) to use whitespace just as with string
 literals.

 Another reason in support of spaces (rather than underscores) to
 separate digit groups: it's the only separator that follows the SI
 standard for representing numbers:

 ??? for numbers with many digits the digits may be divided into
 groups of three by a thin space, in order to facilitate reading.
 Neither dots nor commas are inserted in the spaces between groups
 of three.

But my keyboard doesn't _have_ a thin-space key!

-- 
Grant Edwards   grante Yow! One FISHWICH coming
  at   up!!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Peter Otten
Roy Smith wrote:

 In article [EMAIL PROTECTED],
  Peter Otten [EMAIL PROTECTED] wrote:
 
  I might take it one step further, however, and do:
  
  fields = line.split()[:2]
  a, b = map(int, fields)
  
  in fact, I might even get rid of the very generic, but conceptually
  overkill, use of map() and just write:
  
  a, b = line.split()[:2]
  a = int(a)
  b = int(b)
 
 If you go that route your next step is to introduce another try...except,
 one for the unpacking and another for the integer conversion...
 
 Why another try/except?  The potential unpack and conversion errors exist
 in both versions, and the existing try block catches them all.  Splitting
 the one line up into three with some intermediate variables doesn't change
 that.

As I understood it you didn't just split a line of code into three, but
wanted two processing steps. These logical steps are then somewhat remixed
by the shared error handling. You lose the information which step failed.
In the general case you may even mask a bug.

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


Re: properties setting each other

2008-09-03 Thread Wojtek Walczak
On Wed, 03 Sep 2008 15:57:50 +0200, mk wrote:

 I try to set two properties, value and square in the following code, 
 and arrange it in such way that setting one property also sets another 
 one and vice versa. But the code seems to get Python into infinite loop:

 Is there a way to achieve this goal of two mutually setting properties?

My attempt:
---
import math

class Square(object):
   def __init__(self, val):
  self._square = pow(val, 2)
  self._value = math.sqrt(self.square)

   def getsquare(self):
  return self._square

   def setsquare(self, square):
  self._square = square
  self._value = math.sqrt(self._square)

   square = property(getsquare, setsquare)

   def getvalue(self):
  return self._value

   def setvalue(self, value):
  self._value = value
  self._square = math.pow(value, 2)

   value = property(getvalue, setvalue)


a = Square(5)
print a.square
print a.value
a.value = 10
print a.square
print a.value
a.square = 64
print a.square
print a.value
---

and the result:

$ python sqval.py
25
5.0
100.0
10
64
8.0
$ 

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties setting each other

2008-09-03 Thread Wojtek Walczak
On Wed, 3 Sep 2008 14:31:17 + (UTC), Wojtek Walczak wrote:

 class Square(object):
def __init__(self, val):
   self._square = pow(val, 2)
   self._value = math.sqrt(self.square)
  ^^
or just:
self._value = val

:-)


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties setting each other

2008-09-03 Thread Maric Michaud
Le Wednesday 03 September 2008 15:57:50 mk, vous avez écrit :
 I try to set two properties, value and square in the following code,
 and arrange it in such way that setting one property also sets another
 one and vice versa. But the code seems to get Python into infinite loop:

   import math
   class Squared2(object):

 def __init__(self, val):
 self._internalval=val
 self.square=pow(self._internalval,2)
 
 def fgetvalue(self):
 return self._internalval
 
 def fsetvalue(self, val):
 self._internalval=val
 self.square=pow(self._internalval,2)
 
 value = property(fgetvalue, fsetvalue)

 def fgetsquare(self):
 return self.square
 def fsetsquare(self,s):
 self.square = s
 self.value = math.sqrt(self.square)
 
 square = property(fgetsquare, fsetsquare)

 
   a=Squared2(5)

 Traceback (most recent call last):
    File pyshell#11, line 1, in module
      a=Squared2(5)
    File pyshell#10, line 5, in __init__
      self.square=pow(self._internalval,2)
    File pyshell#10, line 19, in fsetsquare
      self.square = s
    File pyshell#10, line 19, in fsetsquare
      self.square = s
    File pyshell#10, line 19, in fsetsquare
      self.square = s
    File pyshell#10, line 19, in fsetsquare
      self.square = s
    File pyshell#10, line 19, in fsetsquare
      self.square = s
    File pyshell#10, line 19, in fsetsquare

 ...

 Is there a way to achieve this goal of two mutually setting properties?

Your square property is not correctly defined, it recurselively call itself, 
it should be (I also avoided the extra lookup) :

 def fgetsquare(self):
 return self._square
 def fsetsquare(self,s):
 self._square = s
 self.value = math.sqrt(s)

then the fsetvalue will be also be called recursively as it use the square 
property, you should also write it :

 def fsetvalue(self, val):
 self._internalval=val
 self._square=pow(val,2)

*but*, if you want to add more logic in the setters, you could want to add two 
extra methods :

 def _setsquare(self, v) :
 # some extra logic here
 self._square = s

 def fsetsquare(self,s):
 self._setsquare(s)
 self._setvalue = math.sqrt(s)

 def _setvalue(self, val):
 # some extra logic here
 self._internalval=val

 def fsetvalue(self, val):
 self._setvalue(val)
 self._setsquare=pow(val,2)


Note that if one property can really be computed from another, this kind of 
thing could be considered as bad design (except if the computation is heavy).

-- 
_

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


Re: properties setting each other

2008-09-03 Thread Diez B. Roggisch

mk schrieb:

Hello everyone,

I try to set two properties, value and square in the following code, 
and arrange it in such way that setting one property also sets another 
one and vice versa. But the code seems to get Python into infinite loop:


  import math
  class Squared2(object):

def __init__(self, val):
self._internalval=val
self.square=pow(self._internalval,2)
   
def fgetvalue(self):

return self._internalval
   
def fsetvalue(self, val):

self._internalval=val
self.square=pow(self._internalval,2)
   
value = property(fgetvalue, fsetvalue)


def fgetsquare(self):
return self.square
def fsetsquare(self,s):
self.square = s
self.value = math.sqrt(self.square)
   
square = property(fgetsquare, fsetsquare)



  a=Squared2(5)


Traceback (most recent call last):
  File pyshell#11, line 1, in module
a=Squared2(5)
  File pyshell#10, line 5, in __init__
self.square=pow(self._internalval,2)
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare
self.square = s
  File pyshell#10, line 19, in fsetsquare

...

Is there a way to achieve this goal of two mutually setting properties?



Better to make the getter for square return the square of value, and the 
setter of square compute the root  set that. Like this:


class Squared2(object):

def __init__(self, value):
self.value = value


@apply
def squared():
def fset(self, squared):
self.value = math.sqrt(squared)

def fget(self):
return self.value ** 2

return property(**locals())

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


Re: properties setting each other

2008-09-03 Thread Bruno Desthuilliers

mk a écrit :

Hello everyone,

I try to set two properties, value and square in the following code, 
and arrange it in such way that setting one property also sets another 
one and vice versa. But the code seems to get Python into infinite loop:



  import math
  class Squared2(object):

def __init__(self, val):
self._internalval=val
self.square=pow(self._internalval,2)


the 'internal' prefix is already implied by the '_'. And your __init__ 
code is a useless duplication of fsetvalue, so just use the property and 
get rid of copy-pasted code.




def fgetvalue(self):
return self._internalval


the '_' prefix already means 'internal'. The convention here would be to 
name the attribute '_value' (to make clear it's the implementation 
support for the 'value' property). Also, your property getter and setter 
should also be marked as implementation using the '_' prefix - they are 
implementation detail, not part of your class API.



def fsetvalue(self, val):
self._internalval=val
self.square=pow(self._internalval,2)
   
value = property(fgetvalue, fsetvalue)


def fgetsquare(self):
return self.square
def fsetsquare(self,s):
self.square = s


Hem... Notice something here ?


self.value = math.sqrt(self.square)
   
square = property(fgetsquare, fsetsquare)


Your fsetsquare implementation is broken - it calls itself recursively. 
You have to use different names for the property and the 'implementation 
attribute' for the property. But even if you fix this, you'll have 
another infinite recursion between the two setters.


The simplest solution : don't call one property from the other, do 
direct attribute access within the setters:


import math

class Squared2(object):
def __init__(self, value):
self.value=value

def _fgetvalue(self):
return self._value
def _fsetvalue(self, value):
self._value=value
self._square=pow(value,2)
value = property(_fgetvalue, _fsetvalue)

def _fgetsquare(self):
return self._square
def _fsetsquare(self,square):
self._square = square
self._value = math.sqrt(square)
square = property(_fgetsquare, _fsetsquare)


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


Re: properties setting each other

2008-09-03 Thread Maric Michaud
Le Wednesday 03 September 2008 16:44:10 Maric Michaud, vous avez écrit :
          def _setsquare(self, v) :
                  # some extra logic here
                  self._square = s

          def fsetsquare(self,s):
                  self._setsquare(s)
                  self._setvalue = math.sqrt(s)

          def _setvalue(self, val):
                  # some extra logic here
                  self._internalval=val

          def fsetvalue(self, val):
                  self._setvalue(val)
                  self._setsquare=pow(val,2)

Oh sorry for this last version the setters should be :

  def fsetsquare(self,s):
  self._setsquare(s)
  self._setvalue = math.sqrt(self.square)

  def fsetvalue(self, val):
  self._setvalue(val)
  self._setsquare=pow(self.value, 2)

as we don't know what is done in _setXXX methods.

-- 
_

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


Re: Numeric literal syntax

2008-09-03 Thread Grant Edwards
On 2008-09-03, Ben Finney [EMAIL PROTECTED] wrote:

 Another reason in support of spaces (rather than underscores) to
 separate digit groups: it's the only separator that follows the SI
 standard for representing numbers:

 ??? for numbers with many digits the digits may be divided into
 groups of three by a thin space, in order to facilitate reading.
 Neither dots nor commas are inserted in the spaces between groups
 of three.

 URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4

 This isn't binding upon Python, of course. However, it should
 be a consideration in choosing what separator convention to
 follow.

I don't think that standard is applicable.  It's a typesetting
style guide. It also references superscripts, half-high
centered dots, the cross multiplication symbol, the degree
symbol and tons of other things which, like the thin space,
can't be represented using the most common text encodings.

It's quite explicit that the separator is a thin space, which
one presumes would not be considered white space for
tokenizing purposes.  We don't have a thin-space, and allowing
spaces within numerical literals would throw a major
monkey-wrench into a lot of things (like data files whose
values are separated by a single space).

I suppose you could have a different format for literals in
program source and for the operands to int() and float(), but
that feels like a bad idea.

-- 
Grant Edwards   grante Yow! Pardon me, but do you
  at   know what it means to be
   visi.comTRULY ONE with your BOOTH!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Serial I/O problem with pywin32 ?

2008-09-03 Thread Xavier
I tried under Linux... same problem.
So... it may comes from my little lines of code... or from my GPS.
--
http://mail.python.org/mailman/listinfo/python-list


os.system dual behaviour

2008-09-03 Thread iu2
Hi guys

I do

os.system('ls  e')

On one linux machine it emits ls output to the file e as expected.
On another linux machine it emits ls to the standard output, and
nothing to e!
Both machines run Fedora linux.

The command ls  e entered at the shell (no python) behaves ok on
both machines.

Why?? How can I solve this?

Your help will be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Serial I/O problem with pywin32 ?

2008-09-03 Thread Diez B. Roggisch

Xavier schrieb:

Hi,

I try to access to a Bluetooth GPS data-logger with Python. I use
pySerial.

Sending and receiving little messages (~100 char) works fine. However,
when I ask the GPS to dump the trails, it returns some Mbytes and here
is the problem : in the stream of bytes, I randomly losts chunks of
~100bytes.

I tried USPP and pyBlueZ instead of pySerial : same problem.

It doesn't like it is a bufferoverun bug from me because :
 - the GPS seems to wait when I do not read the stream,
 - there is never more than 200 inWainting() characters,
 - my code to test it is quite simple :

  seriallink = serial.Serial(COM40)
  fileName = data.dump
  out = open(fileName, 'w')
  while 1:
c = seriallink.read()
out.write( %0.2X % ord(c))
print *,
  out.close()

(with pyBluez :
sock=BluetoothSocket( RFCOMM )
sock.connect((00:0A:..., 1)))

I tried my program on two different PC with two Bluetooth dongle,
(with pySerial, USPP, pyBluez).
The same things are :
 - windows
 - the GPS (which works fine with the dumper program of the
constructor)
 - pyWin32

I've found another guy with a similar problem :
http://www.generation-nt.com/reponses/rs232-entraide-142097.html
He says:
 - no problem with little messages
 - lost of one byte every hour when receiving a lot of data

Any known problems with pywin32 and serial I/O when downloading a big
stream of data ?


From my experience with serial lines I'd say: that's the culprit. They 
tend to be rather unreliable, as there is no real protocol ensuring data 
integrity.


You might consider downloading chunks of data if that's somehow 
possible, and re-try failed chunks.


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


Re: Numeric literal syntax

2008-09-03 Thread bearophileHUGS
Ben Finney:
 … for numbers with many digits the digits may be divided into
 groups of three by a thin space, in order to facilitate reading.
 Neither dots nor commas are inserted in the spaces between groups
 of three.
 URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4
 This isn't binding upon Python, of course. However, it should be a
 consideration in choosing what separator convention to follow.

It confirms what I say :-) A thin space doesn't break the gestalt of
the number, while a normal space, especially if you use a not
proportional font with good readability (and characters well spaced)
breaks the single gestalt of the number.

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


Re: properties setting each other

2008-09-03 Thread mk


Thanks to everyone for answers..

*but*, if you want to add more logic in the setters, you could want to add two 
extra methods :


 def _setsquare(self, v) :
 # some extra logic here
 self._square = s

 def fsetsquare(self,s):
 self._setsquare(s)
 self._setvalue = math.sqrt(s)

 def _setvalue(self, val):
 # some extra logic here
 self._internalval=val

 def fsetvalue(self, val):
 self._setvalue(val)
 self._setsquare=pow(val,2)



Thanks for that, I'll keep that in mind.


Note that if one property can really be computed from another, this kind of 
thing could be considered as bad design (except if the computation is heavy).


Hmm, why? Is the line of thinking smth like: because the variables 
should be kept to minimum and they should be calculated at the moment 
they are needed?



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


Re: Numeric literal syntax

2008-09-03 Thread Cliff
On Sep 2, 12:34 am, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Ben Finney wrote:
  I would argue that the precedent, already within Python, for using a
  space to separate pieces of a string literal, is more important than
  precedents from other programming languages.

 that precedent also tells us that the whitespace approach is a common
 source of errors.  taking an approach that's known to be error-prone and
 applying it to more cases isn't necessarily a great way to build a
 better language.

 /F

Also a source of mental complexity.  The two proposals (whitespace vs.
underscores) are not just a question of what character to use, it's a
question of whether to create an integer (and possibly other numeric
type) literal that allows delimiters, or to allow separate literals to
be concatenated.  In the second case, which of the following would be
proper syntax?

0b1001 0110
0b1001 0b0110

In the first case, the second literal, on its own, is an octal
literal, but we expect it to behave as a binary literal.  In the
second case, we have more consistency with string literals (with which
you can do this: abc r'''\def''') but we lose the clarity of using
the concatenation to make the whole number more readable.

On the other hand, 0b1001_0110 has one clear meaning.  It is one
literal that stands alone.  I'm not super thrilled about the look (or
keyboard location) of the underscore, but it's better than anything
else that is available, and works within a single numeric literal.
For this reason I am +0 on the underscore and -1 on the space.

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


Re: properties setting each other

2008-09-03 Thread Maric Michaud
Le Wednesday 03 September 2008 17:40:43 mk, vous avez écrit :
  Note that if one property can really be computed from another, this kind
  of thing could be considered as bad design (except if the computation is
  heavy).

 Hmm, why? Is the line of thinking smth like: because the variables
 should be kept to minimum and they should be calculated at the moment
 they are needed?

Because you have to make extra effort to keep the logical relation between 
value and square. self._square is not really needed, and what is not needed 
is just extra hassle.

Doesn't it clear that your code is more hard to maintain than the 
alternative :

class Squared(object):

def __init__(self, val):
self._val=val

def fgetvalue(self):
return self._val
def fsetvalue(self, val):
self._val=val
value = property(fgetvalue, fsetvalue)

def fgetsquare(self):
return self.value ** 2
def fsetsquare(self,s):
self.value = math.sqrt(s)
square = property(fgetsquare, fsetsquare)



-- 
_

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


PyGUI as a standard GUI API for Python?

2008-09-03 Thread Michael Palmer
As anyone knows, the state of Python GUI programming is a little
fractured at this time, with many toolkits, wrappers and meta-wrappers
dead and alive, with or without documentation.

I've come across two projects that have the appeal of striving for
simple, pythonic APIs: PyGUI and wax.  The latter is a wrapper around
wxPython. It is  lacking documentation but actually quite usable and
concise. The other, PyGUI, has an even nicer API and more docs but has
relatively few widgets implemented at this time. It also strives for
compatibility with several toolkits (two at this time), which I think
is the right idea.

So far, development of PyGUI seems to be a one-man effort, and it may
be slowed down by the attempt to develop the API and the
implementations concurrently. Could it be useful to uncouple the two,
such that the API would be specified ahead of the implementation? This
might make it easier for people to contribute implementation code and
maybe port the API to additional toolkits. It seems that this approach
has been quite successful in case of the Python database API. That API
defines levels of compliance, which might be a way of accommodating
different GUI toolkits as well.

I may be underestimating the difficulties of my proposed approach - I
don't have much practical experience with GUI programming myself.

Best, Michael

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


Coming from .NET and VB and C

2008-09-03 Thread ToPostMustJoinGroup22
I'm coming from a .NET, VB, C background.

C was good, and VB was better (with all of its libraries).  Than .NET
came along and all the libraries you can require are ready to go.  I
have no preference with MySQL or SQL, stored procedures or ad-hoc
queries.

SO, I'm interested in using my Google App space (free 500MB) to
develop a quick database application.  Using Python.  I found Dive
Into Python which I will be reading shortly.

Any suggestions for someone new to the scene like me?
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGUI as a standard GUI API for Python?

2008-09-03 Thread Diez B. Roggisch

Michael Palmer schrieb:

As anyone knows, the state of Python GUI programming is a little
fractured at this time, with many toolkits, wrappers and meta-wrappers
dead and alive, with or without documentation.

I've come across two projects that have the appeal of striving for
simple, pythonic APIs: PyGUI and wax.  The latter is a wrapper around
wxPython. It is  lacking documentation but actually quite usable and
concise. The other, PyGUI, has an even nicer API and more docs but has
relatively few widgets implemented at this time. It also strives for
compatibility with several toolkits (two at this time), which I think
is the right idea.


I disagree with that. Meta-wrappers like this will always suffer from 
problems, as they have difficulties providing a consistent api. For 
example wx is said to be very windows-toolkit-centric in it's API. Yes I 
know that it works under Linux with GTK, but it does not come as natural .



So far, development of PyGUI seems to be a one-man effort, and it may
be slowed down by the attempt to develop the API and the
implementations concurrently. Could it be useful to uncouple the two,
such that the API would be specified ahead of the implementation? This
might make it easier for people to contribute implementation code and
maybe port the API to additional toolkits. It seems that this approach
has been quite successful in case of the Python database API. That API
defines levels of compliance, which might be a way of accommodating
different GUI toolkits as well.

I may be underestimating the difficulties of my proposed approach - I
don't have much practical experience with GUI programming myself.


I think you do. The reason for the various toolkits is not because of 
python - it's the proliferation of toolkits that exist out there. As 
long as none of these is the winner (and it doesn't look is if that's 
to happen soon), I doubt that one API to rule them all will exist - they 
all have their different strengths and weaknesses, and a python-API 
should reflect these.


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


Re: Coming from .NET and VB and C

2008-09-03 Thread Simon Brunning
2008/9/3 ToPostMustJoinGroup22 [EMAIL PROTECTED]:
 Any suggestions for someone new to the scene like me?

Welcome!

There's a number of resources that you might find useful here:
http://wiki.python.org/moin/BeginnersGuide

-- 
Cheers,
Simon B.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Coming from .NET and VB and C

2008-09-03 Thread Eric Wertman
  Using Python.  I found Dive Into Python which I will be reading shortly

The title of the book is good advice all by itself.  Especially with
prior programming experience, you'll get started very quickly.  What
will take longer is the assimilation of some of python's neater and
more idiomatic features, like list comprehensions and generators.
Also, the fact that strings are immutable threw me off a little the
first day or two.

If you stick with it, I think you'll find those little things to be
your favorite parts though.  Certainly I use list comprehensions all
the time now, when I used to not use them at all.

In about 90% or more of cases, you can avoid doing things that you do
routinely in other languages..  mostly by iterating directly over
things you don't need counter variables or intermediate variable
names.  In fact, I find myself going back through old code and
removing variables pretty frequently.

I'm sure there's a lot more.  Personally I find it a lot of fun to code in.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-03 Thread Marc 'BlackJack' Rintsch
On Wed, 03 Sep 2008 03:09:18 -0400, Derek Martin wrote:

 On Wed, Sep 03, 2008 at 06:40:10AM +, Marc 'BlackJack' Rintsch
 wrote:
 On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote:
 
  And if they model an action there must be some way to activate the
  action
  
  That's a reasonable assumption, but as I also said, the object might
  just describe the action -- essentially the equivalent of a struct in
  C.
 
 ``struct``\s in C describe *actions*!?  Functions do this.
 
 struct run {
   int speed;
   direction_type direction;
 };

Guess what, I don't like the name because it doesn't describe an action 
but a state of, e.g. a `Runner`.  :-)

  but the instances of `Popen` are no actions.  There's no way to
  execute a `Popen` instance.
  
  Yes there is... you execute it when you instantiate the object.
 
 But then the instance itself isn't an action but the result of one.
 
 So?  A class doesn't represent an action, remember?  It represents a
 thing.  Isn't that what you said?

Yes and that's why the type name should not describe the action but the 
the thing that results from it.  IMHO.  But I said that already.

  Maybe from your POV.  Facts:  It doesn't use the `popen()` function
  
  So?  Neither does the C version of popen(), but that function is
  still called popen()!
 
 Now you lost me.  The C version of `popen()` isn't recursive, why on
 earth should it be, so what's that statement supposed to mean!?
 
 Sorry, did I go too fast for you?  Your facts seem to be suggesting
 that for Python's Popen class to be named Popen, it should use the C
 popen() function.

So you imply that I think any function should only have a name of a 
function it uses under the hood!?  I still don't get that sentence.

 Sorry, but you are contradicting yourself (repeatedly), and your
 arguments don't make any sense.

I don't contradict myself.  Either you are playing silly naming games 
with `popen()` on different levels (concept, Popen, popen() (Python),
popen() (C)) or you just don't *want* to understand my arguments.

I understand your arguments why you think `Popen` is a proper name, but 
don't share them.  It's okay for me if you don't like my arguments 
against it and for something like `Process`, but telling me they don't 
make any sense and patronizing me doesn't make your arguments more 
convincing.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Writing Unicode to database using ODBC

2008-09-03 Thread Mudcat
In short what I'm trying to do is read a document using an xml parser
and then upload that data back into a database. I've got the code more
or less completed using xml.etree.ElementTree for the parser and dbi/
odbc for my db connection.

To fix problems with unicode I built a work-around by mapping unicode
characters to equivalent ascii characters and then encoding everything
to ascii. That allowed me to build the application and debug it
without running into problems printing to file or stdout to screen.

However, now that I've got all that working I'd like to simply take
the unicode data from the xml parser and then pass it directly into
the database (which is currently set up for unicode data). I've run
into problems and just can't figure why this isn't working.

The breakdown is occurring when I try to execute the db query:

  cur.execute( query )

Fairly straightforward. I get the following error:

  File atp_alt.py, line 273, in dbWrite
cur.execute( query )
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in
position 3
79: ordinal not in range(128)

I've verified that query is of type unicode by checking the type a
statement or two earlier (output: type 'unicode').

So then I thought maybe the odbc execute just can't handle unicode
data. But when I do the following command:

  query = query.encode('utf-8')

It actually works. So apparently execute can handle unicode data. The
problem now is that basically the data has been encoded twice and is
in the wrong format when I pull it from the database:

 a
u'+CMGL: (\xe2\u20ac\u0153REC UNREAD\xe2\u20ac\x9d,\xe2\u20ac\x9dREC
READ\xe2\u20ac\x9d,\xe2\u20ac\x9dSTO UNSENT\xe2\u20ac\x9d,\xe2\u20ac
\x9dSTO SENT\xe2\u20ac\x9d,\xe2\u20ac\x9dALL\xe2\u20ac\x9d) OK'
 print a
+CMGL: (“REC UNREADâ€�,â€�REC READâ€�,â€�STO UNSENTâ€�,â€�STO SENTâ
€�,â€�ALLâ€�) OK

The non-alpha characters should be double-quotes. It works correctly
if I copy/paste into the editor:

 d
u'\u201cREC'
 print d
“REC
 d.encode('utf-8')
'\xe2\x80\x9cREC'
 type(d.encode('utf-8'))
type 'str'


I can then decode the string to get back the proper unicode data. I
can't do that with the data out of the db because it's of the wrong
type for the data that it has.

I think the problem is that I'm having to encode data again to force
it into the database, but how can I use the odbc.execute() function
without having to do that?
--
http://mail.python.org/mailman/listinfo/python-list

Using strftime

2008-09-03 Thread frankrentef
I have one line of code that put's an old date in my code.


ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008')



What I wish to do in another similiar line is have the field populated
with the current system date?  How best to do this?  I've read some of
the strftime documentation but as of yet I'm unable to get it to work
correctly.


Help is appreciated.

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


Help needed to freeze a script.

2008-09-03 Thread LB
  Hi,

I would like to freeze a numpy based script in order to have an
application which could run without having to install numpy and cie.

Indeed, I'm not root on the targeted computer and I can't easily
make a complete install of numpy and scipy.

So I decided to test the freeze.py tool shipped with python2.5.
To complicate matters, I must say that I only have a local
installation
of python2.5 and numpy.

I used the following command line :

 python2.5 ../Python-2.5.1/Tools/freeze/freeze.py ~/Python/numpy/test_freeze.py

At first sight, it seems to be fine, as I saw numpy in the liste of
frozen dependancies :
[...]
freezing numpy ...
freezing numpy.__config__ ...
freezing numpy._import_tools ...
freezing numpy.add_newdocs ...
freezing numpy.core ...
freezing numpy.core._internal ...
freezing numpy.core.arrayprint ...
freezing numpy.core.defchararray ...
freezing numpy.core.defmatrix ...
freezing numpy.core.fromnumeric ...
freezing numpy.core.info ...
freezing numpy.core.memmap ...
freezing numpy.core.numeric ...
freezing numpy.core.numerictypes ...
freezing numpy.core.records ...
freezing numpy.ctypeslib ...
  [...]
freezing numpy.version ...

But at the end I saw this message :
Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib
_heapq
  [...]
numpy.core._dotblas numpy.core._sort numpy.core.multiarray
numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite
numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand
operator parser pyexpat readline
  [...]
Now run make to build the target: test_weibull

I runned make without any problem but the final application didn't
work :
% ./test_freeze
Traceback (most recent call last):
  File /home/loic/Python/numpy/test_freeze.py, line 8, in module
import numpy as np
 [...]
  File /home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/
core/__init__.py, line 5, in module
import multiarray
ImportError: No module named multiarray

Is there any known issue when freezing a numpy based script ?
I should add that I configured my PYTHONPATH to match my local
installation
  echo $PYTHONPATH
/home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/
loic/tmp/bluelagoon/lib/python2.5/site-packages/:

and this local installation work fine :
 python2.5 -c 'import numpy; print numpy.__version__; import 
 numpy.core.multiarray; print no pb'

1.2.0b2
no pb

Have you got any recipe to freeze numpy based script ?

Regards,

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


RE: Using strftime

2008-09-03 Thread Ahmed, Shakir

You can try

Import time
mytimeymd = time.strftime('%y%m%d')

print mytimeymd


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
frankrentef
Sent: Wednesday, September 03, 2008 1:21 PM
To: python-list@python.org
Subject: Using strftime

I have one line of code that put's an old date in my code.


ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008')



What I wish to do in another similiar line is have the field populated
with the current system date?  How best to do this?  I've read some of
the strftime documentation but as of yet I'm unable to get it to work
correctly.


Help is appreciated.

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

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


RE: Help on try-except

2008-09-03 Thread Matthew Burns
The reason it takes so long is you are not using xrange
The range function iterates through the entire data set EVERY time,
regardless of whether it needs to
This increases processer use EXPONENTIALLY as that number gets larger.
I am not quite sure how xrange works, but it keeps only one number in memory
at any time
In fact, I never use range any more, I always use xrange.

ALL YOUR BASE ARE BELONG TO US
http://allyourbase.planettribes.gamespy.com/video1_view.shtml


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf
Of [EMAIL PROTECTED]
Sent: Tuesday, September 02, 2008 4:57 PM
To: python-list@python.org
Subject: Python-list Digest, Vol 60, Issue 30

Send Python-list mailing list submissions to
python-list@python.org

To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
[EMAIL PROTECTED]

You can reach the person managing the list at
[EMAIL PROTECTED]

When replying, please edit your Subject line so it is more specific than
Re: Contents of Python-list digest...

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


Re: Is try-except slow?

2008-09-03 Thread Fredrik Lundh

process wrote:


is this faster btw? I guess big doesn't help, it's only retrieved once
anyway? But is rows retrieved in every loop? the python interpreter
aint too smart?



def getPixels(fileName):
im = PIL.Image.open(fileName)
colors = []
r, c = im.size
big = range(0, c)
rows = range(0, r)
for y in big:
row = []
for x in rows:
color = im.getpixel((x,y))
row.append(color)
colors.append(row)
return numpy.array(colors)


you'd probably get more done if you read the replies you get a bit more 
carefully.  Robert Kern suggesting using numpy.asarray earlier:


def getPixels(fileName):
im = PIL.Image.open(fileName)
return numpy.asarray(im)

if you want to work with pixels on the Python level, use im.getdata() or 
the pixel access object returned by im.load().


/F

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


Looking for File comparison utility that produces actual differences

2008-09-03 Thread dudeja . rajat
Hi,

I looking for a file comparison utility in Python that works like
'diff' command in Unix and 'comp' in Windows.
The present 'cmd'  in filecmp module only presents output in the form
of 1 or 0 i.e whether the 2 files differ or not?

So, I'm lookin for something that generates actual differences and
moreover it is cross platform as well. As I need that same thing in
both my windows and linux box.


Even if it is a utlility please suggest.

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for File comparison utility that produces actual differences

2008-09-03 Thread Wojtek Walczak
On Wed, 3 Sep 2008 19:40:40 +0100, [EMAIL PROTECTED] wrote:

 I looking for a file comparison utility in Python that works like
 'diff' command in Unix and 'comp' in Windows.
 The present 'cmd'  in filecmp module only presents output in the form
 of 1 or 0 i.e whether the 2 files differ or not?

In python it's called difflib. Try to import it.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGUI as a standard GUI API for Python?

2008-09-03 Thread Michael Palmer
On Sep 3, 12:57 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Michael Palmer schrieb:

  The other, PyGUI, has an even nicer API and more docs but has
  relatively few widgets implemented at this time. It also strives for
  compatibility with several toolkits (two at this time), which I think
  is the right idea.

 I disagree with that. Meta-wrappers like this will always suffer from
 problems, as they have difficulties providing a consistent api. For
 example wx is said to be very windows-toolkit-centric in it's API. Yes I
 know that it works under Linux with GTK, but it does not come as natural .

wax actually does a nice job at wrapping wxPython with a cleaner API.

  So far, development of PyGUI seems to be a one-man effort, and it may
  be slowed down by the attempt to develop the API and the
  implementations concurrently. Could it be useful to uncouple the two,
  such that the API would be specified ahead of the implementation? This
  might make it easier for people to contribute implementation code and
  maybe port the API to additional toolkits. It seems that this approach
  has been quite successful in case of the Python database API. That API
  defines levels of compliance, which might be a way of accommodating
  different GUI toolkits as well.

  I may be underestimating the difficulties of my proposed approach - I
  don't have much practical experience with GUI programming myself.

 I think you do. The reason for the various toolkits is not because of
 python - it's the proliferation of toolkits that exist out there.

Right. But that is similar to the situation with relational databases.
There are so many of them that it's impossible to include an adapter
to each of them in the stdlib. The next best thing is to provide a
high-level API that abstracts away the differences.

 As long as none of these is the winner (and it doesn't look is if that's
 to happen soon), I doubt that one API to rule them all will exist - they
 all have their different strengths and weaknesses, and a python-API
 should reflect these.

I rather think that a standard API would cover a reasonable subset -
it should NOT contain the idiosyncrasies of each individual toolkit.

The anygui project, which has been dormant for a while, is another
attempt at a high-level api. Apparently, it tried to implement
backends for a lot of toolkits - which again may have been to
ambitious an agenda. Maybe someone who was involved in that project
might provide some insight.




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


Re: Looking for File comparison utility that produces actual differences

2008-09-03 Thread Jeff McNeil
On Sep 3, 2:40 pm, [EMAIL PROTECTED] wrote:
 Hi,

 I looking for a file comparison utility in Python that works like
 'diff' command in Unix and 'comp' in Windows.
 The present 'cmd'  in filecmp module only presents output in the form
 of 1 or 0 i.e whether the 2 files differ or not?

 So, I'm lookin for something that generates actual differences and
 moreover it is cross platform as well. As I need that same thing in
 both my windows and linux box.

 Even if it is a utlility please suggest.

 Thanks and regards,
 Rajat

What about the difflib module?

[EMAIL PROTECTED] test]$ cat file_one
abcd
1234
-
[EMAIL PROTECTED] test]$ cat file_two
abcd
12345
-
[EMAIL PROTECTED] test]$


[EMAIL PROTECTED] test]$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type help, copyright, credits or license for more information.
 import difflib
 for i in difflib.context_diff(open(file_one).readlines(), 
 open(file_two).readlines()):
... print i,
...
***
---
***
*** 1,3 
  abcd
! 1234
  -
--- 1,3 
  abcd
! 12345
  -


Also, see http://docs.python.org/lib/module-difflib.html.

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


creating a similar object from an derived class

2008-09-03 Thread Scott
Let's say I have an object:

class foo():
   def create_another()
   return foo()

   def blah():
   x = self.create_another()
   ... do something with X

Now I create a inherited class of this object:

class bar(foo):
...

If I call bar.create_another(), it will return a foo() instead of a
bar(). This isn't what I want. I would like bar.create_another() to
create an instance for bar(). Obviously I can do this by overriding
create_another, i.e.

class bar(foo):
def create_another()
return bar()

However, is there a way for me to modify foo() so that it
automatically creates objects of the derived class, so that I don't
have to continue to redefine create_another() ?

For example, I tried the following:

def create_another()
return self.type()()

but it did not work.

Thanks,
Scott


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


Re: max(), sum(), next()

2008-09-03 Thread Laszlo Nagy

[EMAIL PROTECTED] wrote:

Empty Python lists [] don't know the type of the items it will
contain, so this sounds strange:

  

sum([])


0

Because that [] may be an empty sequence of someobject:
  


You are right in that sum could be used to sum arbitrary objects. 
However, in 99.99% of the cases, you will be summing numerical values. 
When adding real numbers, the neutral element is zero. ( X + 0 = X) It 
is very logical to return zero for empty sequences.


Same way, if we would have a prod() function, it should return one for 
empty sequences because X*1 = X. The neutral element for this operation 
is one.


Of course this is not good for summing other types of objects. But how 
clumsy would it be to use


sum( L +[0] )

or

if L:
value = sum(L)
else:
value = 0

instead of sum(L).

Once again, this is what sum() is used for in most cases, so this 
behavior is the expected one.


Another argument to convince you: the sum() function in SQL for empty 
row sets returns zero in most relational databases.


But of course it could have been implemented in a different way... I 
believe that there have been excessive discussions about this decision, 
and the current implementation is very good, if not the best.


Best,

Laszlo



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


Re: PyGUI as a standard GUI API for Python?

2008-09-03 Thread Diez B. Roggisch

Michael Palmer schrieb:

I disagree with that. Meta-wrappers like this will always suffer from
problems, as they have difficulties providing a consistent api. For
example wx is said to be very windows-toolkit-centric in it's API. Yes I
know that it works under Linux with GTK, but it does not come as natural .


wax actually does a nice job at wrapping wxPython with a cleaner API.


wax wraps wx. It does not wrap PyQt, Tk, win32, GTK and whatnot. That 
was what I was talking about.



Right. But that is similar to the situation with relational databases.
There are so many of them that it's impossible to include an adapter
to each of them in the stdlib. The next best thing is to provide a
high-level API that abstracts away the differences.


As long as none of these is the winner (and it doesn't look is if that's
to happen soon), I doubt that one API to rule them all will exist - they
all have their different strengths and weaknesses, and a python-API
should reflect these.


I rather think that a standard API would cover a reasonable subset -
it should NOT contain the idiosyncrasies of each individual toolkit.


And thus reduce the usability massively. A reasonable subset is already 
included in python, with tkinter, available on a wide range of plattforms.


Yet still people strive for the various other toolkits, because they 
miss richer widgets, gui-designers (an important topic you don't cover 
at all) or e.g. multi-threading capabilities.



The anygui project, which has been dormant for a while, is another
attempt at a high-level api. Apparently, it tried to implement
backends for a lot of toolkits - which again may have been to
ambitious an agenda. Maybe someone who was involved in that project
might provide some insight.


Sure, that would be interesting.

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


Re: Help needed to freeze a script.

2008-09-03 Thread Michael Palmer
On Sep 3, 1:30 pm, LB [EMAIL PROTECTED] wrote:
   Hi,

 I would like to freeze a numpy based script in order to have an
 application which could run without having to install numpy and cie.

 Indeed, I'm not root on the targeted computer and I can't easily
 make a complete install of numpy and scipy.

 So I decided to test the freeze.py tool shipped with python2.5.
 To complicate matters, I must say that I only have a local
 installation
 of python2.5 and numpy.

 I used the following command line :

  python2.5 ../Python-2.5.1/Tools/freeze/freeze.py 
  ~/Python/numpy/test_freeze.py

 At first sight, it seems to be fine, as I saw numpy in the liste of
 frozen dependancies :
 [...]
 freezing numpy ...
 freezing numpy.__config__ ...
 freezing numpy._import_tools ...
 freezing numpy.add_newdocs ...
 freezing numpy.core ...
 freezing numpy.core._internal ...
 freezing numpy.core.arrayprint ...
 freezing numpy.core.defchararray ...
 freezing numpy.core.defmatrix ...
 freezing numpy.core.fromnumeric ...
 freezing numpy.core.info ...
 freezing numpy.core.memmap ...
 freezing numpy.core.numeric ...
 freezing numpy.core.numerictypes ...
 freezing numpy.core.records ...
 freezing numpy.ctypeslib ...
   [...]
 freezing numpy.version ...

 But at the end I saw this message :
 Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib
 _heapq
   [...]
 numpy.core._dotblas numpy.core._sort numpy.core.multiarray
 numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite
 numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand
 operator parser pyexpat readline
   [...]
 Now run make to build the target: test_weibull

 I runned make without any problem but the final application didn't
 work :
 % ./test_freeze
 Traceback (most recent call last):
   File /home/loic/Python/numpy/test_freeze.py, line 8, in module
 import numpy as np
  [...]
   File /home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/
 core/__init__.py, line 5, in module
 import multiarray
 ImportError: No module named multiarray

 Is there any known issue when freezing a numpy based script ?
 I should add that I configured my PYTHONPATH to match my local
 installation
   echo $PYTHONPATH
 /home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/
 loic/tmp/bluelagoon/lib/python2.5/site-packages/:

 and this local installation work fine :

  python2.5 -c 'import numpy; print numpy.__version__; import 
  numpy.core.multiarray; print no pb'

 1.2.0b2
 no pb

 Have you got any recipe to freeze numpy based script ?

 Regards,

 --
 LB

Did you try py2exe instead of freeze? On the page

http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules

there is only one brief mention of numpy packaging troubles,
suggesting that it might work better. I have used py2exe in the past
without much trouble.
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.system dual behaviour

2008-09-03 Thread Emile van Sebille

iu2 wrote:

Hi guys

I do

os.system('ls  e')

On one linux machine it emits ls output to the file e as expected.
On another linux machine it emits ls to the standard output, and
nothing to e!
Both machines run Fedora linux.

The command ls  e entered at the shell (no python) behaves ok on
both machines.

Why?? How can I solve this?


Why?? I don't know.  But you could try the commands module to work 
around it...


open(e,'w').writelines(commands.getoutput('ls'))


HTH,

Emile

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


Re: properties setting each other

2008-09-03 Thread Bruno Desthuilliers

Maric Michaud a écrit :

Le Wednesday 03 September 2008 17:40:43 mk, vous avez écrit :

Note that if one property can really be computed from another, this kind
of thing could be considered as bad design (except if the computation is
heavy).

Hmm, why? Is the line of thinking smth like: because the variables
should be kept to minimum and they should be calculated at the moment
they are needed?


Because you have to make extra effort to keep the logical relation between 
value and square. self._square is not really needed, and what is not needed 
is just extra hassle.


Doesn't it clear that your code is more hard to maintain than the 
alternative :


class Squared(object):

def __init__(self, val):
self._val=val

def fgetvalue(self):

return self._val
def fsetvalue(self, val):
self._val=val
value = property(fgetvalue, fsetvalue)

def fgetsquare(self):
return self.value ** 2
def fsetsquare(self,s):
self.value = math.sqrt(s)
square = property(fgetsquare, fsetsquare)


FWIW, if there's no computation on getting or setting value, you can 
make it a plain attribute.


But while it's quite clear that in this example use case it would be 
better  to have only one property (weither square or value, depending on 
which is the most often use), things are not always that simple in real 
world code, and - as you mentionned - there may be times where you have 
interdependant properties and really want to avoid recomputing the same 
thing over and over. Now there's no one size fits all solution here - 
it's an optimization problem, and as such depends on real use cases.




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


Re: Is try-except slow?

2008-09-03 Thread Robert Kern

Steven D'Aprano wrote:

On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote:


ssecorp wrote:

or why does this take so god damn long time?

Several reasons. One of which is that try: except: is slow.



I beg to differ. Setting up a try...except block is very fast. Here's an 
example in Python 2.5:




from timeit import Timer
Timer('len(abc)').repeat()

[0.27346706390380859, 0.1530919075012207, 0.14886784553527832]

Timer('''try:

... len(abc)
... except:
... pass
... ''').repeat()
[0.27847194671630859, 0.19191384315490723, 0.19077491760253906]

The difference (approx 0.04 microseconds) applicable to setting up the 
try...except block is trivial, of the same magnitude as a pass statement:



Timer('pass').repeat()

[0.059719085693359375, 0.060056924819946289, 0.059512138366699219]


However, *catching* the exception may be relatively slow:


Timer('''try:

... len(abc)  # raise a NameError
... except:
... pass
... ''').repeat()
[3.2067418098449707, 2.7088210582733154, 1.9558219909667969]


You're right. My mistake. I was misremembering Guido's old essay about try: 
except: versus if: else:.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: creating a similar object from an derived class

2008-09-03 Thread Matimus
On Sep 3, 12:09 pm, Scott [EMAIL PROTECTED] wrote:
 Let's say I have an object:

 class foo():
    def create_another()
        return foo()

    def blah():
        x = self.create_another()
        ... do something with X

 Now I create a inherited class of this object:

 class bar(foo):
     ...

 If I call bar.create_another(), it will return a foo() instead of a
 bar(). This isn't what I want. I would like bar.create_another() to
 create an instance for bar(). Obviously I can do this by overriding
 create_another, i.e.

 class bar(foo):
     def create_another()
         return bar()

 However, is there a way for me to modify foo() so that it
 automatically creates objects of the derived class, so that I don't
 have to continue to redefine create_another() ?

 For example, I tried the following:

 def create_another()
     return self.type()()

 but it did not work.

 Thanks,
 Scott

This works:

 class C(object):
...   @classmethod
...   def create_another(cls):
...   return cls()
...
 class D(C):
...   pass
...
 d = D()
 e = d.create_another()
 isinstance(e, D)
True


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


Re: Coming from .NET and VB and C

2008-09-03 Thread Bruno Desthuilliers

ToPostMustJoinGroup22 a écrit :

I'm coming from a .NET, VB, C background.

C was good, and VB was better (with all of its libraries).  Than .NET
came along and all the libraries you can require are ready to go.  I
have no preference with MySQL or SQL, stored procedures or ad-hoc
queries.

SO, I'm interested in using my Google App space (free 500MB) to
develop a quick database application.  Using Python.  I found Dive
Into Python which I will be reading shortly.

Any suggestions for someone new to the scene like me?


The worst thing you could would be to try to write VB in Python. While 
Python may not  - for someone coming from more mainstream languages - 
look as weird as Lisp or Haskell or etc..., it's really a totally 
different beast. Lurking here, trying to answer other's persons 
questions, and reading other peoples solution might be a good way to 
learn idiomatic Python.

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


Re: creating a similar object from an derived class

2008-09-03 Thread Bruno Desthuilliers

Scott a écrit :

Let's say I have an object:


s/object/class/


class foo():
   def create_another()
   return foo()


class Foo(object):
def create_another(self):
return Foo()


   def blah():


 def blah(self):

   x = self.create_another()
   ... do something with X



Now I create a inherited class of this object:

class bar(foo):


class Bar(Foo):

...

If I call bar.create_another(), it will


Actually, it will raise a TypeError...


return a foo() instead of a
bar(). This isn't what I want. I would like bar.create_another() to
create an instance for bar().


   def create_another(self)
   return type(self)()


And while you're at it, since - at least in this concrete case - you 
need access to the class but not to the instance, you could make it a 
classmethod:


class Foo(object):
@classmethod
def create_another(cls):
return cls()


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


Re: Usual practice: running/testing modules in a package

2008-09-03 Thread Casey
On Aug 26, 10:21 pm, Casey [EMAIL PROTECTED] wrote:
 On Aug 12, 9:57 pm, alito [EMAIL PROTECTED] wrote:



  A wrapper on the level up works:

  ~/python$ cat importercaller.py
  from testpackage import config
  config.hello()

  ~/python$ python importercaller.py
  hello

  So, how do I run these modules without writing a wrapper script for
  each one?



It looks like PEP 366 [http://www.python.org/dev/peps/pep-0366/] will
solve this issue.
--
http://mail.python.org/mailman/listinfo/python-list


python/xpath question..

2008-09-03 Thread bruce
morning

i apologize up front as this is really more of an xpath question..

in my python, i'm using the xpath function to iterate/parse some html. i can
do something like

s=d.xpath(//tr/td/text())
count=len(s)

and get the number of nodes that have text

i can then do something like
s=d.xpath(//tr/td)
count2=len(s)

and get the number of total nodes...
by subtracting, i can get the number of nodes, without text.. is there an
easier way??!!
count2-count

ie, if i have something like
tr
td/td
tdfoo/td
/tr

is there a way to get the count that there is a single td node with
text()=

thanks


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


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

 Roy Smith wrote:
 
  In article [EMAIL PROTECTED],
   Peter Otten [EMAIL PROTECTED] wrote:
  
   I might take it one step further, however, and do:
   
   fields = line.split()[:2]
   a, b = map(int, fields)
   
   in fact, I might even get rid of the very generic, but conceptually
   overkill, use of map() and just write:
   
   a, b = line.split()[:2]
   a = int(a)
   b = int(b)
  
  If you go that route your next step is to introduce another try...except,
  one for the unpacking and another for the integer conversion...
  
  Why another try/except?  The potential unpack and conversion errors exist
  in both versions, and the existing try block catches them all.  Splitting
  the one line up into three with some intermediate variables doesn't change
  that.
 
 As I understood it you didn't just split a line of code into three, but
 wanted two processing steps. These logical steps are then somewhat remixed
 by the shared error handling. You lose the information which step failed.
 In the general case you may even mask a bug.
 
 Peter

Well, what I really wanted was two conceptual steps, to make it easier for 
a reader of the code to follow what it's doing.  My standard for code being 
adequately comprehensible is not that the reader *can* figure it out, but 
that the reader doesn't have to exert any effort to figure it out.  Or even 
be aware that there's any figuring-out going on.  He or she just reads it.
--
http://mail.python.org/mailman/listinfo/python-list


Late initialization using __getattribute__

2008-09-03 Thread bukzor
I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the delattr call because it throws an AttributeError (although I
don't know why).



class LateInitMixIn(object):
def __init__(self):
print LateInit initialization
self.inited = False
def __getattribute__(self, attr):
print Doing __getattribute__
getattr = lambda attr:object.__getattribute__(self, attr)
if not getattr(inited):
super(LateInitMixIn, self).__init__()
setattr(self, inited, True)
#delattr(self, __getattribute__)
return getattr(attr)



class Base(object):
def __init__(self):
print Base initialization
self.base = True
class LateInit(LateInitMixIn, Base): pass

def main():
S = LateInit()
print S
print
print Should do Base init after now
print S.base
print S.base

if __name__==__main__: main()




This gives the following output:
LateInit initialization
__main__.LateInit object at 0x2a960c1c50

Should do Base init after now
Doing __getattribute__
Base initialization
True
Doing __getattribute__
True


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


Python on the web - newby question

2008-09-03 Thread SimonPalmer
Apologies in advance if this is either a) the wrong board or b) been
answered a million times elsewhere, but...

I have been given an assignment to get a python module up and running
behind an existing web site.  At the moment the rest of the site is
developed in PHP but the hosts have said they will provide python
support for free, although they haven't given any more details than
that, so I'm not sure exactly what that means.  All reasonably
encouraging though.

I'm a newbie to python but quite experienced with Java/J2EE/JBoss.
What I need to know is how I get python running on the server and what
tools/middleware I would need to have installed on the host's machines
to be able to support my python modules.

Again, apologies if this is the wrong place but I'm a bit lost and
would really appreciate some pointers.

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


Re: PyGUI as a standard GUI API for Python?

2008-09-03 Thread OKB (not okblacke)
Michael Palmer wrote:

 As anyone knows, the state of Python GUI programming is a little
 fractured at this time, with many toolkits, wrappers and meta-wrappers
 dead and alive, with or without documentation.

How about Dabo?  http://www.dabodev.com/


-- 
--OKB (not okblacke)
Brendan Barnwell
Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail.
--author unknown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Late initialization using __getattribute__

2008-09-03 Thread Bruno Desthuilliers

bukzor a écrit :

I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have.


You shouldn't mess with __getattribute__ unless you really know what 
you're doing and are ok to suffer the constant performance hit you'll 
get. Remember that __getattribute__ actually *is* the implementation of 
attribute lookup rules, and is called on each and every attribute 
lookup. Your below snippet would be much better using __getattr__ (which 
is only called as a last resort).



I've commented out
the delattr call because it throws an AttributeError (although I
don't know why).


__getattribute__ belongs to the class, not to the instance. delattr() 
only removes instance attributes. You'd have to remove __getattribute__ 
from the LateInitMixIn class object itself, but then it would break the 
whole thing.





class LateInitMixIn(object):
def __init__(self):
print LateInit initialization
self.inited = False
def __getattribute__(self, attr):
print Doing __getattribute__
getattr = lambda attr:object.__getattribute__(self, attr)
if not getattr(inited):
super(LateInitMixIn, self).__init__()
setattr(self, inited, True)
#delattr(self, __getattribute__)
return getattr(attr)



Here's another possible implementation (which doesn't solve all 
problems, cf below) using __getattr__:


class LateInitMixin(object):
def __init__(self):
print not yet
self.__initialized = False


def __getattr__(self, name):
if self.__initialized:
raise AttributeError(
object %s has no attribute '%s' % (type(self), name)
)
super(LateInitMixin, self).__init__()
self.__initialized = True
return getattr(self, name)

class Base(object):
def __init__(self):
print yet
self.base = True

class LateInit(LateInitMixin, Base):
pass

def main():
print shouldn't init
S = LateInit()
print should init
print S.base

if __name__==__main__:
main()



Ok, now, the other problem : what if Base.__init__ expects args ?

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


Re: Python on the web - newby question

2008-09-03 Thread Bruno Desthuilliers

SimonPalmer a écrit :

Apologies in advance if this is either a) the wrong board or b) been
answered a million times elsewhere, but...

I have been given an assignment to get a python module up and running
behind an existing web site.  At the moment the rest of the site is
developed in PHP but the hosts have said they will provide python
support for free, although they haven't given any more details than
that, so I'm not sure exactly what that means.


Depending on the hosts, this can range from having an antiquated python 
version with only cgi enabled and no way to install anything to the very 
last stable release and (almost) whatever third-part lib / frameworks 
and correct configuration.



 All reasonably
encouraging though.

I'm a newbie to python but quite experienced with Java/J2EE/JBoss.


Quite another world...


What I need to know is how I get python running on the server


For which definition of 'server' ? The computer, or the web server process ?


and what
tools/middleware I would need to have installed on the host's machines
to be able to support my python modules.


Depends on your modules dependencies !-)

More seriously : Python is known has being the language with more web 
frameworks than keywords. IOW, there's no simple straightforward answer 
to your question. Fisrt choose which Python web development solution you 
intend to use, then read the FineManual's deployment section of the 
chosen solution.


You'll find pointers to most web-related libs / frameworks here:
http://wiki.python.org/moin/WebFrameworks
http://wiki.python.org/moin/WebProgramming

Given your situation (Python newcomer with a real job to do), and if 
your job is anything more than a very QD deadsimple task, I'd 
personnaly recommand Django (http://djangiproject.com). Don't let the 
version number fools you (latest version is 1.0 release candidate), 
Django is a mature, solid and proven solution that have years of 
existance, and what they call 1.0rc would be labeled at least 3.5 for 
some other software... It's also mostly documented, and there's a strong 
community around the framework, so you should not have much problem 
getting help.


For any other Python question (I mean, non django-related), you're at 
the right place.


Oh, and yes, if I may suggest a reading:
http://dirtsimple.org/2004/12/python-is-not-java.html

HTH, and welcome on board...
--
http://mail.python.org/mailman/listinfo/python-list


Re: [wwwsearch-general] python mechanize/libxml2dom question

2008-09-03 Thread John J Lee

On Mon, 1 Sep 2008, bruce wrote:
[...]

how can i

[...]

libxml2dom

[...]

Just a general point: try lxml.etree instead?  Friendlier API.


John

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


Re: Late initialization using __getattribute__

2008-09-03 Thread bukzor
On Sep 3, 12:19 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 bukzor a écrit :

  I want to make a MixIn class that waits to initialize its super-
  classes until an attribute of the object is accessed. Not generally
  useful, but desirable in my case. I've written this, and it works, but
  would like to take any suggestions you guys have.

 You shouldn't mess with __getattribute__ unless you really know what
 you're doing and are ok to suffer the constant performance hit you'll
 get. Remember that __getattribute__ actually *is* the implementation of
 attribute lookup rules, and is called on each and every attribute
 lookup. Your below snippet would be much better using __getattr__ (which
 is only called as a last resort).

  I've commented out
  the delattr call because it throws an AttributeError (although I
  don't know why).

 __getattribute__ belongs to the class, not to the instance. delattr()
 only removes instance attributes. You'd have to remove __getattribute__
 from the LateInitMixIn class object itself, but then it would break the
 whole thing.



  class LateInitMixIn(object):
      def __init__(self):
          print LateInit initialization
          self.inited = False
      def __getattribute__(self, attr):
          print Doing __getattribute__
          getattr = lambda attr:object.__getattribute__(self, attr)
          if not getattr(inited):
              super(LateInitMixIn, self).__init__()
              setattr(self, inited, True)
          #delattr(self, __getattribute__)
          return getattr(attr)

 Here's another possible implementation (which doesn't solve all
 problems, cf below) using __getattr__:

 class LateInitMixin(object):
      def __init__(self):
          print not yet
          self.__initialized = False

      def __getattr__(self, name):
          if self.__initialized:
              raise AttributeError(
                  object %s has no attribute '%s' % (type(self), name)
                  )
          super(LateInitMixin, self).__init__()
          self.__initialized = True
          return getattr(self, name)

 class Base(object):
      def __init__(self):
          print yet
          self.base = True

 class LateInit(LateInitMixin, Base):
      pass

 def main():
      print shouldn't init
      S = LateInit()
      print should init
      print S.base

 if __name__==__main__:
      main()

 Ok, now, the other problem : what if Base.__init__ expects args ?

Thanks for the reply. Just to see it not work, I tried to remove
__getattribute__ from LateInitMixIn, but couldn't get it to work.

My Base class is a C class (_mysql.connection from MySQLdb) that
sometimes segfaults if you try to use it before it's fully
initialized, so unfortunately I think I need to use __getattribute__
to do this. I'm doing all this just to make the connection not
actually connect until used.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >