Re: is +=1 thread safe

2008-05-02 Thread Marc 'BlackJack' Rintsch
On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote:

> Of course it's not thread safe.   For the same reason and more basic, 
> even the expression i++ is not thread safe in C++.
> 
> Any such calculation, on modern processors, requires three operations: 
>   retrieve value of i into a register,
>   increment the register
>   write the value into i.

There are no modern processors with an opcode for incrementing a memory
location!?  At least my C64 can do that.  ;-)

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


Re: where do I begin with web programming in python?

2008-05-02 Thread bvidinli
i also asked same question in this list last week.
i found http://www.cherrypy.org/ to be most suitable for me.
it is basic, easy, pure...
it contains its own webserver, very easy to start.

others have many framworks, structures, classes many many..
i wanted a pure web programming system , i found cherrypy.

see you.


2008/5/2 jmDesktop <[EMAIL PROTECTED]>:
> I have been to the main python site, but am still confused.  I have
>  been using .net, so it may be obvious how to do this to everyone
>  else.  I am aware there are various frameworks (Django, Pylons, etc.),
>  but I would like to know how to create web pages without these.  If I
>  have mod_python or fastcgi on apache, where do I start?  I don't have
>  clue where to begin to create a web page from scratch in python.  I am
>  sure I will want to access database, etc., all the "normal" stuff, I
>  just want to do it myself as opposed to the frameworks, for learning.
>
>  Thank you for any help.
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>



-- 
İ.Bahattin Vidinli
Elk-Elektronik Müh.
---
iletisim bilgileri (Tercih sirasina gore):
skype: bvidinli (sesli gorusme icin, www.skype.com)
msn: [EMAIL PROTECTED]
yahoo: bvidinli

+90.532.7990607
+90.505.5667711
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-02 Thread Paul Rubin
AlFire <[EMAIL PROTECTED]> writes:
> But I still can not believe that +=1 is not a thread safe operation.

In CPython I believe it is thread safe, because of the global
interpreter lock.  Thread switches can happen only between bytecode
executions, not in the middle of a bytecode, even though executing a
bytecode can take several machine instructions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-02 Thread Duncan Booth
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote:
> 
>> Of course it's not thread safe.   For the same reason and more basic, 
>> even the expression i++ is not thread safe in C++.
>> 
>> Any such calculation, on modern processors, requires three operations: 
>>   retrieve value of i into a register,
>>   increment the register
>>   write the value into i.
> 
> There are no modern processors with an opcode for incrementing a memory
> location!?  At least my C64 can do that.  ;-)
> 
The operation i++ in C/C++ implies two things: it increments the memory 
location and returns the new result. That means there are at least two ways 
to generate code for this:

   increment memory
   load new value

or

   load value
   incremenent
   store

Neither of these is going to be thread-safe (even on a C64) unless you 
protect the operations somehow. The latter is probably preferred as it only 
implies two operations to memory whereas the former implies three.

Even on your C64 incrementing a memory location involves both a read and a 
write, so if you have a multi-core C64(!) there is still scope for another 
processor to get into the middle of that increment instruction.

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Jeroen Ruigrok van der Werven
-On [20080502 07:51], Ben Finney ([EMAIL PROTECTED]) wrote:
>To my mind, the Python interpreter installed by a package as
>distributed with the OS *is* OS territory and belongs in /usr/bin/.

That's the difference with a distribution, such as Linux, and full OSes ,
such as BSDs or commercial Unix variants. They prefer to keep a pristine
state for the OS vendor files versus what the user can opt to install
himself, hence the /usr/bin - /usr/local/bin separation. Same for sbin, lib,
and so on. It effectively guarantees you can nuke /usr/local without ill
consequences for your OS.

Different philosophies, but after having spent more than 10+ years on too
many Unix and Unix-like systems I know the importance of platform
portability a bit too much and hardcoding a shebang sequence is not the
solution in general. Using env is the, arguably, best solution available.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
Felix, qui potuit rerum cognoscere causas...
--
http://mail.python.org/mailman/listinfo/python-list

Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Duncan Booth
Yves Dorfsman <[EMAIL PROTECTED]> wrote:

> On UNIX, some people use
> #!/usr/bin/env python
> 
> While other use
> #!/usr/bin/python
> 
> Why is one preferred over the other one ?
> 
I don't think the answers so far have communicated what I believe to be the 
important point: it isn't that one is always better than the other, it 
depends on what you are trying to achieve.

The first one runs the Python found from the environment. This means you 
can write a script and expect it to run on systems configured differently. 
You might prefer in some cases to specify a particular version of Python:

#!/usr/bin/env python2.5

The second one runs a specific copy of Python (and here it is even more 
likely that you'll want to specify a particular version). This is important 
if your program is being run as a service or some other background 
situation where the environment isn't set up. For example Subversion hooks 
all run with an empty environment, and cron jobs run with a default 
environment which may not include python (e.g. if it is in /usr/local/bin).


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


Re: help with list comprehension

2008-05-02 Thread George Sakkis
On May 2, 2:17 am, Matimus <[EMAIL PROTECTED]> wrote:

> On May 1, 10:50 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
>
>
>
> > On May 1, 11:46 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
>
> > > Yves Dorfsman wrote:
>
> > > > In the following script, m1() and m2() work fine. I am assuming m2() is
> > > > faster although I haven't checked that (loops through the list twice
> > > > instead of once).
>
> > > Well, let's check it:
>
> > > $ python -m timeit -s "import x" "x.m1()"
> > > 10 loops, best of 3: 6.43 usec per loop
>
> > > $ python -m timeit -s "import x" "x.m2()"
> > > 10 loops, best of 3: 8.34 usec per loop
>
> > > As it turns out, m1 is faster than m2. The reason is that list
> > > comprehensions do the loop in C, whereas the for-append pattern does the
> > > loop on the Python level.
>
> > > > Now what I am trying to do is something like m3(). As currently written
> > > > it does not work, and I have tried different ways, but I haven't managed
> > > > to make it work.
>
> > > > Is there a possibility ? Or is m2() the optimum ?
>
> > > > [...]
> > > > def m1():
> > > >   colours = [ e['colour'] for e in l ]
> > > >   nums    = [ e['num']    for e in l ]
>
> > > > def m2():
> > > >   colours = []
> > > >   nums    = []
> > > >   for e in l:
> > > >     colours.append(e['colour'])
> > > >     nums.append(e['num'])
>
> > > > #def m3():
> > > > #  colours, nums = [ e['colour'], e['num'] for e in l ]
>
> > > m3 doesn't work because you're building a list of 10 color/number pairs
> > > that you're trying to unpack that into just two names. The working
> > > "derivative" of m3 is m1, which is the most natural, fastest and
> > > clearest solution to your problem.
>
> > Another alternative is:
>
> > from operator import itemgetter
>
> > def m3():
> >     colours, nums = zip(*map(itemgetter('colour','num'), l))
>
> > It's slower than m1() but faster than m2(); it's also the most
> > concise, especially if you extract more than two keys.
>
> > George
>
> Why deal with zip and unpacking?

DRY [1].

This seems more obvious to me:
>
> colours, nums = map(itemgetter('colour'), l), map(itemgetter('num'),
> l)

Maybe, but now extend it to three keys. And then four. And then... you
see my point.

George

[1] http://en.wikipedia.org/wiki/Don%27t_repeat_yourself
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-02 Thread Hrvoje Niksic
Paul Rubin  writes:

> AlFire <[EMAIL PROTECTED]> writes:
>> But I still can not believe that +=1 is not a thread safe operation.
>
> In CPython I believe it is thread safe, because of the global
> interpreter lock.  Thread switches can happen only between bytecode
> executions, not in the middle of a bytecode, even though executing a
> bytecode can take several machine instructions.

It's safe when writing extensions in C (because of the GIL), but not
when writing Python code.  Python switches threads after a number of
bytecode instructions, so Python code behaves somewhat like C
multithreaded code on a single CPU -- although there is no true
parallelism, you still have context switches at arbitrary places to
worry about, and still need locks because of them.  Since the +=
operator is not compiled into a single bytecode instruction, it needs
the lock.  x+=1 gets compiled into the following bytecode:

  3   0 LOAD_GLOBAL  0 (x)
  3 LOAD_CONST   1 (1)
  6 INPLACE_ADD
  7 STORE_GLOBAL 0 (x)

If two threads execute that code simultaneously, a thread switch could
easily occur some time between LOAD_GLOBAL and STORE_GLOBAL, causing
the variable to be incremented by 1 instead of by 2.
--
http://mail.python.org/mailman/listinfo/python-list


Re: where do I begin with web programming in python?

2008-05-02 Thread 7stud
On May 1, 3:25 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.
>
> Thank you for any help.

Directions for a simple CGI script:

1) Start apache.

2) Use a text editor to create a webpage with a link:



Python CGI Test




http://localhost/cgi-bin/first.py";>click me





Save that file with a .htm extension anywhere on your computer, e.g.
name the file test.htm and save it in C:\My Documents.


3) The value of the link's href attribute is a special url.  The url
starts with "http://localhost";, or it may need to start with something
like http://localhost:8080"; depending on what port number you
installed Apache on.  If you used the default port when you installed
Apache, then the first part of the url will be "http:/localhost".

The rest of the url is the relative path to your cgi script.  The path
is relative to your Apache2 folder.  For instance, my directory
structure looks like this:

Apache2
htdocs
cgi-bin
first.py
etc.

So the relative path to my cgi script is "/cgi-bin/first.py".

4) Create a cgi script:

#!/usr/bin/env python

#For Windows, instead of the above line use
#something like: #!C:\Python25\python.exe
#instead.  The path after "#!" should be the
#path to wherever python.exe is on your computer.

import cgitb; cgitb.enable()

#The above line will cause error messages to
#be sent to your browser, which is helpful for
#debugging.  Otherwise, your browser will just
#show a blank page when there is an error in your
#script

print "Content-type: text/html"
print
print "Hello World"


The first print statement is the minimum header you need when
responding to a web page.  After you print all the headers you desire,
then you need to print a blank line.  After the blank line, you print
the html that you want the browser to display.


5) On Unix: you have to set the file permissions for your cgi script.
Everyone must be able to read and execute your cgi script:

$ chmod 755 first.py


6) Start your web browser, and click on File>Open and navigate to
your .htm file.  When your html page opens in your browser, click on
the link.  The link will call your python cgi script, the cgi script
will respond my sending some html to your browser, then your browser
will display the html.


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


Re: Simple TK Question - refreshing the canvas when not in focus

2008-05-02 Thread Eric Brunel

On Wed, 30 Apr 2008 20:19:32 +0200, blaine <[EMAIL PROTECTED]> wrote:


On Apr 30, 10:41 am, Peter Otten <[EMAIL PROTECTED]> wrote:

blaine wrote:
> Still doesn't work.  I'm looking into using wx instead...

> This is the full code - does it work for anyone else? Just do a echo
> 'line 0 0 10 10' > dev.file

Haven't tried it, but I think that the problem is that you are updating  
the
UI from the "readthread". A good example to model your app after is  
here:


http://effbot.org/zone/tkinter-threads.htm

Peter


Update: Not only is that a good model, its exactly what I'm trying to
do.  Thanks again!


BTW, instead of reading the queue periodically, you can also use the event  
loop for that: in the secondary thread, generate a custom event using the  
event_generate method. Custom events are enclosed in '<<...>>', the '...'  
can be whatever you like. Be sure to generate the event with the  
when='tail' option or the event might get handled immediatly. To treat the  
event, do a binding on it: it will be called in your main thread. It's a  
common trick to switch threads so that GUI events are treated in the main  
thread and not in secondary ones.


Example:

--
import threading
import time
import Queue
from Tkinter import *

root = Tk()

q = Queue.Queue()

def thread_action():
  i = 1
  while 1:
time.sleep(1)
q.put(i)
root.event_generate('<>', when='tail')
i += 1

v = StringVar()

def ping_received(event):
  v.set(q.get())

Label(root, textvariable=v, width=10).pack()
root.bind('<>', ping_received)

th = threading.Thread(target=thread_action)
th.setDaemon(1)
th.start()

root.mainloop()
--

HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

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


Re: my module and unittest contend over commandline options...

2008-05-02 Thread Duncan Booth
chrisber <[EMAIL PROTECTED]> wrote:

> I've poked around to see if I could delete the options my earlier code
> consumed from the commandline buffer, before invoking unittest, but
> that seems klugy. Instead, I hardwired  in a testing config file name,
> that always has to be local. That works pretty well, but it leaves me
> wonderfing whether there would have been another clean way to allow
> both my test code and unittest to have options without interfering
> with one another.
> 

You can pass argv as a parameter to main(), so I think the best bet is 
simply to build up a new argv with the options that you want to pass 
through.

Another option would be to subclass unittest.TestProgram and override 
parseArgs, but you'd have to copy & modify it as it doesn't seem to have 
been designed to be easily extendable.
--
http://mail.python.org/mailman/listinfo/python-list


get number that is raised to the power of

2008-05-02 Thread Astan Chee

Hi,
Im not sure if this is more of a math question or a python question. I 
have a variable in python:

>>> v = 10.0**n
is there a way to find the value of n if i know only v aside from 
str(v).split('+')[1] ? that seems like too much of a hack and I was 
wondering if there was a faster way of doing it?

Thanks for any pointers
Astan

--
"Formulations of number theory: Complete, Consistent, Non-trivial. Choose two."


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



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


Re: Python's doc problems: sort

2008-05-02 Thread George Neuner
On Wed, 30 Apr 2008 12:35:10 +0200, "John Thingstad"
<[EMAIL PROTECTED]> wrote:

>PÃ¥ Wed, 30 Apr 2008 06:26:31 +0200, skrev George Sakkis  
><[EMAIL PROTECTED]>:
>
>>
>>\|||/
>>  (o o)
>> ,ooO--(_)---.
>> | Please|
>> |   don't feed the  |
>> | TROLL's ! |
>> '--Ooo--'
>> |__|__|
>>  || ||
>> ooO Ooo
>
>Doesn't copying Rainer Joswig's troll warning constitute a copywright  
>infrigment :)

It's not an exact copy of Rainer's so it may be arguable whether it
violates his copyright.  Might have more luck with a trademark
argument - distorted marks may still infringe.

George
--
for email reply remove "/" from address
--
http://mail.python.org/mailman/listinfo/python-list


Re: get number that is raised to the power of

2008-05-02 Thread Marc 'BlackJack' Rintsch
On Fri, 02 May 2008 19:19:07 +1000, Astan Chee wrote:

> Hi,
> Im not sure if this is more of a math question or a python question. I 
> have a variable in python:
>  >>> v = 10.0**n
> is there a way to find the value of n if i know only v aside from 
> str(v).split('+')[1] ? that seems like too much of a hack and I was 
> wondering if there was a faster way of doing it?

That hack isn't even working properly because ``str(10.0**1)`` has no '+'
in its string representation.

Solution:

n = math.log(v, 10)

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


Re: get number that is raised to the power of

2008-05-02 Thread Python.Arno


On 2 mei 2008, at 11:19, Astan Chee wrote:


Hi,
Im not sure if this is more of a math question or a python question.  
I have a variable in python:

>>> v = 10.0**n
is there a way to find the value of n if i know only v aside from  
str(v).split('+')[1] ? that seems like too much of a hack and I was  
wondering if there was a faster way of doing it?

Thanks for any pointers
Astan







the "reverse" of a power to is logarithm
so v = 10**n  <=>  math.log(v,10) = n

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


Python documentation

2008-05-02 Thread admin
Hello,

I have been learning python for some time using the dive into python
book. I am interested to know if anyone can recommend a book which
covers more advanced topics like threading and potentially GUI style
coding.

Regards,

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


Re: dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows

2008-05-02 Thread illume
On May 2, 8:37 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "illume" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | Ah, why is that?
>
> Were any of the reasons given inhttp://www.python.org/dev/peps/pep-0011/
> unclear?
> It appears you are already aware of MS's non-support of Win98


Hello,

It seems the main reason is for ease of maintenance.  However the Pep
title is misleading with regards to win9x+winMe+win2k - which is where
my confusion, questions and argument came from.
"Title: Removing support for little used platforms"

There are still *lots* of people who still use win95, 98, 98se, me,
and win2k - as shown by the statistics I linked to in a previous
post.  If you want more statistics about the number of people using
what OS they are fairly easy to find with a search engine.  One day
win9x will be finally dead, but that's not yet(and the w3c stats show
it's usage actually increasing in march!).

It is probably way too late in the process to put back code - and as
you say no python developers have volunteered.  So I won't argue any
more for it to come back.

We'll just have to recommend a different python implementation than
2.6 or 3.0 for people who want to support people with these old
computers.


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


Re: no cleanup on TERM signal

2008-05-02 Thread Laszlo Nagy

Yves Dorfsman wrote:

I did a few tests with this script:

class byebye:

  def __del__(self):
print 'Bye, bye...'


x = byebye()


x.del() gets executed if:
-I del x, then run gc.collect()
-simply exit the script
-get the script to abort on an exception

But if I kill it with the default signal TERM, the script dies, but I 
don't get the message, so I am assuming that python isn't taking the 
time to cleanup, even though that is (was) what TERM was intended for.
TERM signal is unix specific. There is no special syntax/programming 
structure for signals inside the Python language, since it would be 
platform dependent. For simple client programs, usually it is not needed 
to setup signal handlers because they can easily be controlled in other 
ways.


For sensitive resources, instead of writing __del__ methods, you should 
create a "close()" method. Python does this with file objects, DB API 
2.0 with database connection objects etc. Then you can do


res = create_resource()
try:
   use_resource()
finally:
   res.close() # Must free resource, but the object can still be alive...

It is more common to use signals when you have more threads or child 
processes. You can use something like:


import threading
import signal

stop_requested = threading.Event()
exited_on_sigterm = False

def free_all_resources():
   pass # Free your resources here!

def sigterm_handler(signum, frame):
   """Stop the server gracefully when on SIGTERM."""
   global stop_requested
   global exited_on_sigterm
   exited_on_sigterm = True
   stop_requested.set()
   free_all_resources()

def main():
   global stop_requested
   global exited_on_sigterm

   logger = servicelog.getLogger('main',filename=LOGFILENAME)

   logger.info('Setting up the SIGTERM signal handler.')
   signal.signal(signal.SIGTERM, sigterm_handler) # Setup signal handler

   logger.info('Starting watchdog thread')
   watchdog = WatchDog()
   watchdog.start()

   worker1 = create_worker(stop_requested)
   worker2 = create_worker(stop_requested)
   # etc. Prepare things here...
  
   try:

   try:
   server = create_my_server()
   server.serve_until_not_stopped()  
   except Exception, e:

   logger.error(dumpexc(e))
   raise e
   finally:
   stop_requested.set()  # Ask other threads to stop cooperatively
 
   # Join all threads here

   watchdog.join()
   worker1.join()
   worder2.join()
   # etc. wait for all threads to exit cooperatively.
   if exited_on_sigterm:
   logger.warning('Exited on SIGTERM!')

Best,

  Laszlo

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


Re: get number that is raised to the power of

2008-05-02 Thread Astan Chee



Python.Arno wrote:

the "reverse" of a power to is logarithm
so v = 10**n  <=>  math.log(v,10) = n

Arno


Im so ashamed of myself for not thinking in logs.
I must be dreaming again.
Thanks for the help.

--
"Formulations of number theory: Complete, Consistent, Non-trivial. Choose two."


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



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


Re: get number that is raised to the power of

2008-05-02 Thread Boris Borcic

Marc 'BlackJack' Rintsch wrote:

On Fri, 02 May 2008 19:19:07 +1000, Astan Chee wrote:


Hi,
Im not sure if this is more of a math question or a python question. I 
have a variable in python:

 >>> v = 10.0**n
is there a way to find the value of n if i know only v aside from 
str(v).split('+')[1] ?


Astan, you could try something like (n for n in range(1,100) if 
10.0**n==v).next() or like len(str(int(v)))-1


that seems like too much of a hack and I was 
wondering if there was a faster way of doing it?


Faster ?! How fast do you need it to be ?



That hack isn't even working properly because ``str(10.0**1)`` has no '+'
in its string representation.


OTOH "%.0e" % (10.0**1) does
...but "%.0e" % (10.0**-1) of course doesn't



Solution:

n = math.log(v, 10)

Ciao,
Marc 'BlackJack' Rintsch


Beware of floating point approximations, though. Eg

>>> assert log(10**3,10)==3

Traceback (most recent call last):
  File "", line 1, in 
assert log(10**3,10)==3
AssertionError

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


Re: dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows

2008-05-02 Thread Christian Heimes
illume schrieb:
> There are still *lots* of people who still use win95, 98, 98se, me,
> and win2k - as shown by the statistics I linked to in a previous
> post.  If you want more statistics about the number of people using
> what OS they are fairly easy to find with a search engine.  One day
> win9x will be finally dead, but that's not yet(and the w3c stats show
> it's usage actually increasing in march!).

Windows 2000 is still supported by Python 2.6 and 3.0 although you may
get into trouble if you haven't installed at least SP4.

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


Re: no cleanup on TERM signal

2008-05-02 Thread Christian Heimes
Laszlo Nagy schrieb:
> For sensitive resources, instead of writing __del__ methods, you should
> create a "close()" method. Python does this with file objects, DB API
> 2.0 with database connection objects etc. Then you can do
> 
> res = create_resource()
> try:
>use_resource()
> finally:
>res.close() # Must free resource, but the object can still be alive...

You can replace the try/finally code with a "with resource:
do_something()" block if the object supporst the context manager protocol.

If you want to run some code during the shutdown phase of the Python
process you can register a callback function in the "atexit" module.

> It is more common to use signals when you have more threads or child
> processes. You can use something like:

Do NOT mix threads and signals. It's usually a very bad idea and may
lead to surprising side effects. Signals are only handled by the main
thread.

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


creating a list from a inconsistent text file

2008-05-02 Thread Jetus
I have a comma delimited file that is separated by comma's, and then
sometimes by ","

c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211",
1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 "
c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211",
2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 "
c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211",
3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 "


I would like to pick out data in a particular column. So am I right in
thinking that I would need to covert each line into a list, then
choose the appropriate column via a index?

How do I convert that line into a list?
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a list from a inconsistent text file

2008-05-02 Thread Marc 'BlackJack' Rintsch
On Fri, 02 May 2008 04:14:47 -0700, Jetus wrote:

> I have a comma delimited file that is separated by comma's, and then
> sometimes by ","
> 
> c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211",
> 1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 "
> c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211",
> 2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 "
> c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211",
> 3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 "

The items are always delimited by commas but some items themselves contain
a comma and therefore are enclosed in double quotes.  So it's not
inconsistent.

> How do I convert that line into a list?

Use the `csv` module in the standard library.

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


Re: portable fork+exec/spawn

2008-05-02 Thread Nick Craig-Wood
Brendan Miller <[EMAIL PROTECTED]> wrote:
>  On Fri, 02 May 2008 13:25:55 +1000, Ben Finney wrote:
> 
> > URL:http://docs.python.org/lib/module-subprocess.html
> 
>  Awesome. This is exactly what I was hoping existed.

subprocess works well for spawn process, send input, receive output,
read exit code type jobs.

For jobs which require interactivity ie send input, receive output,
send input, receive output, ... it doesn't work well.  There isn't a
good cross platform solution for this yet.  pyexpect works well under
unix and is hopefully being ported to windows soon.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Custom Classes?

2008-05-02 Thread J. Clifford Dyer
On Thu, 2008-05-01 at 17:31 -0500, Victor Subervi wrote:
> On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote:
> Post working code, and I'll answer your actual question.
> 
> Good grief!  The code is *not* double spaced! Take a look. Click to
> the end of the first line and hit the right arrow key, and see for
> yourself.  As for not initializing w, well, I did in my code and just
> forgot to cut and paste that. Same with the except. Sorry on those.
> And yes, I pull out try clauses when I need to look at stacks. Here:

Taking a closer look--it's still double spaced, but I'm sure that's just
something funky in how it's getting rendered along the way.  

That said, your code still doesn't work.  After removing your try
statements, and the corresponding except-pass blocks, I get the
following problems:

Traceback (most recent call last):
  File "test.py", line 5, in 
os.remove(getpic)
NameError: name 'os' is not defined

and when I fix that:

Traceback (most recent call last):
  File "test.py", line 34, in 
print ''
% pic

Please test your code snippet before you post it.  Testing the program
you extracted it from is not sufficient.

On line 34 (or thereabouts--I had to add a line for import os, and
stripped out all blank lines, since my email client is still rendering
it double spaced), I think you wanted "x" instead of str(x).  At least,
that's what your generated script wants.  str(x) takes the value of the
variable x (not yet defined), and converts it to a str.  It does not
give you a str with a value of "x".  

As for the generated script, why are you creating that on the fly every
time?  Why not just create it as an independent python file?  When you
want an image displayed in another HTML file, static or generated, just
point your src to that python file with the appropriate arguments.



Also, remove the line that says "print 'Content-Type: text/html'."  You
only need one content type, and it should be image/jpeg, or whatever
type your images are.  If you are going to have a few pngs in there as
well, for example, you'll need some mechanism for determining what type
of image the file actually is, and outputting the appropriate header
from:

Content-Type: image/jpeg
Content-Type: image/png
Content-Type: image/gif

This could be by checking the file extension, probing the file itself,
or by including the mime-type in your pics dictionary like so:

pics = {1: ('pic1', 'image/jpeg'), 2: ('pict_num_two', 'image/png')} 


Then, of course, you'll have to revise how you retrieve the information.

That should be enough to get you moving in the right direction.

Cheers,
Cliff
> 
> 
> w = 0
> 
> 
> try:
> 
>   w += 1
> 
>   getpic = "getpic" + str(w) + ".py"
> 
>   try:
> 
> os.remove(getpic)
> 
>   except:
> 
> pass
> 
>   code = """
> 
> #!/usr/local/bin/python
> 
> import cgitb; cgitb.enable()
> 
> import MySQLdb
> 
> import cgi
> 
> import sys,os
> 
> sys.path.append(os.getcwd())
> 
> from login import login
> 
> user, passwd, db, host = login()
> 
> form = cgi.FieldStorage()
> 
> picid = int(form["id"].value)
> 
> x = int(form["x"].value)
> 
> pics =
> {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
> 
> 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
> 
> pic = pics[x]
> 
> print 'Content-Type: text/html'
> 
> db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
> 
> cursor= db.cursor()
> 
> sql = "select " + pic + " from products where id='" + str(picid) +
> "';"
> 
> cursor.execute(sql)
> 
> content = cursor.fetchall()[0][0].tostring()
> 
> cursor.close()
> 
> print 'Content-Type: image/jpeg'
> 
> print
> 
> print content
> 
> """
> 
>   script = open(getpic, "w")
> 
>   script.write(code)
> 
>   print ''
> % pic
> 
>   print '\n' % (getpic, d,
> y)
> 
> except:
> 
>   pass
> 
> 
> TIA,
> Victor
> 
-- 
Oook!
J. Cliff Dyer
Carolina Digital Library and Archives
UNC Chapel Hill

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

Re: no cleanup on TERM signal

2008-05-02 Thread Duncan Booth
Christian Heimes <[EMAIL PROTECTED]> wrote:

>> res = create_resource()
>> try:
>>use_resource()
>> finally:
>>res.close() # Must free resource, but the object can still be
>>alive... 
> 
> You can replace the try/finally code with a "with resource:
> do_something()" block if the object supporst the context manager
> protocol. 
> 

or replace it with:

 with contextlib.closing(create_resource()) as res:
 do_something()

if the object does not support the context manager protocol.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Ben Finney
Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]> writes:

> -On [20080502 07:51], Ben Finney ([EMAIL PROTECTED]) wrote:
> >To my mind, the Python interpreter installed by a package as
> >distributed with the OS *is* OS territory and belongs in /usr/bin/.
> 
> That's the difference with a distribution, such as Linux, and full
> OSes , such as BSDs or commercial Unix variants. They prefer to keep
> a pristine state for the OS vendor files versus what the user can
> opt to install himself, hence the /usr/bin - /usr/local/bin
> separation.

Fine so far. /usr/local/ is certainly for "what the (system
administrator) user opts to install themselves".

> It effectively guarantees you can nuke /usr/local without ill
> consequences for your OS.

You say this as though it's a property that a GNU/Linux distribution
doesn't have. But the "keep /usr/local/ untouched by OS packages"
approach taken by GNU/Linux *also* means that /usr/local/ can be blown
away without ill consequences for the OS. So I don't see why you draw
that distinction here.

The difference seems to be that Python is an OS-installable package on
GNU/Linux, and thus gets installed to the OS-packaged location. So the
default Python installation should work.

Whereas if Python is *not* installed from an OS package, it's up to
the sys admin to ensure that it works -- not up to my program. So I
don't see the point in making it work by default, when what I want for
my program is that it works *with the default Python*, not with some
non-default installation.

-- 
 \   "Truth is stranger than fiction, but it is because fiction is |
  `\ obliged to stick to possibilities, truth isn't."  -- Mark |
_o__)   Twain, _Following the Equator_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread D'Arcy J.M. Cain
On Fri, 02 May 2008 15:50:22 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> > You have lived a sheltered life.  Not every packaging system puts the
> > executible in /usr/bin.  Many systems use /usr/local/bin.
> 
> They use that for the operating-system-installed default Python
> interpreter? Colour me incredulous.

OK, let me get out my crayons.  However, note that I did not say
"operating-system-installed."  I said a packaging system puts it
there.  In fact, the NetBSD packaging system works on many systems
including Linux and thus is not an operating system packager.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Ben Finney
"D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:

> On Fri, 02 May 2008 13:24:01 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
> > I much prefer "#! /usr/bin/python" because I want my Python
> > programs to, by default, be run with the default Python, and
> > depend on Python being installed by the operating system's package
> > manager. On systems that use shebang lines and that actually have
> > standardised filesystem locations, the default Python is found at
> > '/usr/bin/python'.
> 
> You have lived a sheltered life.  Not every packaging system puts the
> executible in /usr/bin.  Many systems use /usr/local/bin.

"D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:

> On Fri, 02 May 2008 15:50:22 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
> > They use that for the operating-system-installed default Python
> > interpreter? Colour me incredulous.
> 
> OK, let me get out my crayons.  However, note that I did not say
> "operating-system-installed."

That is, however, the context I've been explicitly using since this
sub-thread began.

The OP was asking why people prefer on over the other. My answer is
that I prefer specifying "give me the default OS Python" because
anything not installed by the OS is to non-standardised for me to
worry about.

Others may prefer something different, but then they get to wear
whatever problems occur as a result of that choice. I continue to be
bemused by that preference, and nothing that I've seen so far in this
thread illuminates the issue more.

-- 
 \ "Nothing so needs reforming as other people's habits."  -- Mark |
  `\   Twain, _Pudd'n'head Wilson_ |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python documentation

2008-05-02 Thread Mike Driscoll
On May 2, 4:34 am, [EMAIL PROTECTED] wrote:
> Hello,
>
> I have been learning python for some time using the dive into python
> book. I am interested to know if anyone can recommend a book which
> covers more advanced topics like threading and potentially GUI style
> coding.
>
> Regards,
>
> Ronald

Lutz's book, "Programming Python" covers a lot of advanced topics,
including building various GUI-oriented programs with Tkinter. There's
also "Core Python Programming" by Chun, which has some good internals
stuff in it.

I prefer using wxPython for my GUI work, so I'll also recommend Robin
Dunn's "wxPython in Action".

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


Re: Custom Classes?

2008-05-02 Thread Victor Subervi
Thank you for your patience. I apologize for so many errors. Also,
apparently your email client renders those double-spaces whereas mine does
not. Hopefully the below is better:

#!/usr/bin/python

import MySQLdb
import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()

pic = "pic1"
w = 20
x = 0
d = 6
y = 1
getpic = "getpic" + str(w) + ".py"
try:
  os.remove(getpic)
except:
  pass
code = """
#!/usr/local/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()
form = cgi.FieldStorage()
picid = int(form["id"].value)
x = int(form["x"].value)
pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
pic = pics[x]
db = MySQLdb.connect(host, user, passwd, db)
cursor= db.cursor()
sql = "select %s from products where id='%s';" % (pic, str(picid))
cursor.execute(sql)
content = cursor.fetchall()[0][0].tostring()
cursor.close()
print 'Content-Type: image/jpeg'
print
print content
"""
script = open(getpic, "w")
script.write(code)
# print '' % (str(x),  pic)
# print '\n' % (getpic, d, y)
print '\n'



Now, on those last 3 lines, I am having trouble with this error being thrown
that I don´t understand:
ValueError: unpack list of wrong size
If I surf to the given url, the image appears! So what gives?? Furthermore,
the code works just fine from where it was lifted.
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Re: creating a list from a inconsistent text file

2008-05-02 Thread Jetus
On May 2, 7:19 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 02 May 2008 04:14:47 -0700, Jetus wrote:
> > I have a comma delimited file that is separated by comma's, and then
> > sometimes by ","
>
> > c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211",
> > 1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 "
> > c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211",
> > 2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 "
> > c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211",
> > 3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 "
>
> The items are always delimited by commas but some items themselves contain
> a comma and therefore are enclosed in double quotes.  So it's not
> inconsistent.
>
> > How do I convert that line into a list?
>
> Use the `csv` module in the standard library.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Hello Marc;
Thanks for the input! I am worried about the comma in the "" data
items, how do I tell Python to look for the "" data first, then use
the comma separator?
--
http://mail.python.org/mailman/listinfo/python-list


Re: is +=1 thread safe

2008-05-02 Thread Diez B. Roggisch

Duncan Booth schrieb:

Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:


On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote:

Of course it's not thread safe.   For the same reason and more basic, 
even the expression i++ is not thread safe in C++.


Any such calculation, on modern processors, requires three operations: 
  retrieve value of i into a register,

  increment the register
  write the value into i.

There are no modern processors with an opcode for incrementing a memory
location!?  At least my C64 can do that.  ;-)

The operation i++ in C/C++ implies two things: it increments the memory 
location and returns the new result. That means there are at least two ways 
to generate code for this:


   increment memory
   load new value

or

   load value
   incremenent
   store

Neither of these is going to be thread-safe (even on a C64) unless you 
protect the operations somehow. The latter is probably preferred as it only 
implies two operations to memory whereas the former implies three.


This is not entirely right. increment is usually atomic (at least for 
single-core processors), so you don't suffer from a load/store being 
interrupted.


Of course it can happen that the previous or later loading of the value 
for computational purposes is interrupted by another thread. But you 
have the guarantee that all incs (and decs) are counted, in contrast to 
what the OP observed with python.


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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Thorsten Kampe
* Ben Finney (Fri, 02 May 2008 23:30:01 +1000)
> The OP was asking why people prefer on over the other. My answer is
> that I prefer specifying "give me the default OS Python" because
> anything not installed by the OS is to non-standardised for me to
> worry about.
> 
> Others may prefer something different, but then they get to wear
> whatever problems occur as a result of that choice. I continue to be
> bemused by that preference, and nothing that I've seen so far in this
> thread illuminates the issue more.

You're missing the point. Apart from the really dubious terms you use 
("OS installable package"), using env in the first line has exactly the 
effect to use the default path of Python (which is the first entry in 
your path) and not some hard-coded path (which might not even exist).

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


Re: Do you know of a much simpler way of writing a program that writes a program?

2008-05-02 Thread Nicola Musatti
On May 2, 3:50 pm, mcse jung <[EMAIL PROTECTED]> wrote:
> Here is asample program that writes a program and then executes it.
> Do you knowof a much simpler way of writing a program that writes a program?

Use a templating engine, such as Cheetah: http://www.cheetahtemplate.org/

Cheers,
Nicola Musatti
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Ben Finney <[EMAIL PROTECTED]> wrote:

> Whereas if Python is *not* installed from an OS package, it's up to
> the sys admin to ensure that it works -- not up to my program. So I
> don't see the point in making it work by default, when what I want for
> my program is that it works *with the default Python*, not with some
> non-default installation.

Ben,

Have you ever shipped software to a customer?  Imagine the following 
conversation:

Customer: "Your product is broken.  It says it can't find python, and I 
know I have it installed".

Vendor: "Where do you have it installed?"

Customer: "In /opt/bin/python"

Vendor: "Oh, that's your problem, it HAS to be in /usr/bin/python".

Customer: "I can't install it there because .  If you can't make your product work without requiring 
me to install python in /usr/bin, I'm afraid I can't buy your product".

Vendor: "No problem sir, I'll be happy to tell our sales folks to stop 
bothering you".

If you want to hard-code /usr/bin/python into your application, that's your 
decision.  If you would like to take on the task of convincing every 
sysadmin in the world to do things the way you think they should be done, 
have fun.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread D'Arcy J.M. Cain
On Fri, 02 May 2008 23:30:01 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> The OP was asking why people prefer on over the other. My answer is
> that I prefer specifying "give me the default OS Python" because
> anything not installed by the OS is to non-standardised for me to
> worry about.

As someone else pointed out, not all the world is Linux.  So your
version of Linux (I'm not sure whether it is true for all versions or
not) delivers Python as part of the OS.  That is simply not true of the
whole world.  Some OS distributions have an adjunct facility for
installing packages but they are not part of the OS.  Some systems
don't even have that and people must download packages such as Python
and install them manually.  Even on Linux there are people who won't
install binaries and use NetBSD's pkgsrc instead.  Clearly that cannot
install into /usr/bin since it is not part of the OS.

Certainly #! /usr/bin/python is fine if you never expect your software
to run outside of your own little corner of the world but you asked why
people prefer the env version and the answer is that we want to write
software that runs everywhere that Python runs.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: where do I begin with web programming in python?

2008-05-02 Thread [EMAIL PROTECTED]
On May 2, 10:07 am, bvidinli <[EMAIL PROTECTED]> wrote:
> i also asked same question in this list last week.
> i foundhttp://www.cherrypy.org/to be most suitable for me.
> it is basic, easy, pure...
> it contains its own webserver, very easy to start.
>
> others have many framworks, structures, classes many many..
> i wanted a pure web programming system , i found cherrypy.
>
> see you.
>
> 2008/5/2 jmDesktop <[EMAIL PROTECTED]>:
>
> > I have been to the main python site, but am still confused.  I have
> >  been using .net, so it may be obvious how to do this to everyone
> >  else.  I am aware there are various frameworks (Django, Pylons, etc.),
> >  but I would like to know how to create web pages without these.  If I
> >  have mod_python or fastcgi on apache, where do I start?  I don't have
> >  clue where to begin to create a web page from scratch in python.  I am
> >  sure I will want to access database, etc., all the "normal" stuff, I
> >  just want to do it myself as opposed to the frameworks, for learning.
>
> >  Thank you for any help.
> >  --
> >  http://mail.python.org/mailman/listinfo/python-list
>
> --
> Ý.Bahattin Vidinli
> Elk-Elektronik Müh.
> ---
> iletisim bilgileri (Tercih sirasina gore):
> skype: bvidinli (sesli gorusme icin,www.skype.com)
> msn: [EMAIL PROTECTED]
> yahoo: bvidinli
>
> +90.532.7990607
> +90.505.5667711

I agree. Try cherrypy. I was able to write simple issue tracking
system for my project with basic web interface within 2 weeks.
Prior to this I had no web development experience at all. It was
really easy with cherrypy to start.
--
http://mail.python.org/mailman/listinfo/python-list


Do you know of a much simpler way of writing a program that writes a program?

2008-05-02 Thread mcse jung
Here is asample program that writes a program and then executes it.  
Do you knowof a much simpler way of writing a program that writes a program?
 
"""
-
Name:_writePythonCode.py
Purpose: This script writes Python code and thentransfers control to it.
 
Author:  MCSEJUNG
 
Created: 2008/05/01
RCS-ID:  $Id: _writePythonCode.py $
Copyright:   (c) 2008
Licence: GPL
   This program is free software; you canredistribute it and/or modify
   it under the terms of the GNU General PublicLicense as published by
   the Free Software Foundation; either version2 of the License
   (at your option) any later version.
 
   This program is distributed in the hope thatit will be useful,
   but WITHOUT ANY WARRANTY; without even theimplied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULARPURPOSE.  See the
   GNU General Public License for more details.
 
   You should have received a copy of the GNUGeneral Public License
   along with this program; if not, write tothe Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
Maintenance:MCSEJUNG 2008/05/01 This script writes Python code and then 
transfers controlto it.
-
"""
__version__= "$Revision:  80101 $"
# $Source$
 
# Rememberto document each paragraph with a purposeful short description
 
#if__name__ == "__main__":
 
#Print thestart time of this process
import time
start =time.localtime(time.time())
year,month, day, hour, minute, second, weekday, yearday, daylight = start
print"Process Started", "%02d:%02d:%02d" % (hour, minute,second)
 
header1 ="""
-
Name:_generatedPython.py
Purpose: This script was built by_writePythonCode.py
 
Author:  MCSEJUNG
 
Created: 2008/05/01
RCS-ID:  $Id: _generatedPython.py $
Copyright:   (c) 2008
Licence: GPL
   This program is free software; you canredistribute it and/or modify
   it under the terms of the GNU General PublicLicense as published by
   the Free Software Foundation; either version2 of the License
   (at your option) any later version.
 
   This program is distributed in the hope thatit will be useful,
   but WITHOUT ANY WARRANTY; without even theimplied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULARPURPOSE.  See the
   GNU General Public License for more details.
 
   You should have received a copy of the GNUGeneral Public License
   along with this program; if not, write tothe Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
Maintenance:MCSEJUNG 2008/05/01 This script was built by _writePythonCode.py
-
"""
 
header2 ="""
# $Source$
 
# Rememberto document each paragraph with a purposeful short description
 
#if__name__ == "__main__":
 
#Print thestart time of this process
"""
 
filePathName= 'C:\\Python25\\Lib\\_myStuff'
fileInName= '_generatedPython.py'
filegTName= filePathName + '\\' +fileInName
gT =open(filegTName, 'w')
 
gT.write('"""'+ header1 + '"""' + '\n')
gT.write('__version__= "$Revision:  80101 $"'+ '\n')
gT.write('"""'+ header2 + '"""' + '\n')
gT.write('importtime'+'\n')
gT.write('start= time.localtime(time.time())'+'\n')
gT.write('year,month, day, hour, minute, second, weekday, yearday, daylight = 
start'+'\n')
gT.write('print"Generated Process Started", "%02d:%02d:%02d" % (hour,minute, 
second)'+'\n')
#---
gT.write('print"start"'+'\n')
gT.write('fori in [0,4,8,12,16,12,8,12,8,12,16,12,8,4,8,12,16,12,8,4,0]:'+'\n')
gT.write('print "-"*i'+'\n')
gT.write('print"end"'+'\n')
#---
gT.write('#Calculatethe processes duration; format and print the start time, 
stop time, andduration'+'\n')
gT.write('stop= time.localtime(time.time())'+'\n')
gT.write('syear,smonth, sday, shour, sminute, ssecond, sweekday, syearday, 
sdaylight =stop'+'\n')
gT.write(''+'\n')
gT.write('thour   = shour'+'\n')
gT.write('tminute = sminute'+'\n')
gT.write('tsecond= ssecond'+'\n')
gT.write(''+'\n')
gT.write('iftsecond < second:'+'\n')
gT.write('tminute = tminute - 1'+'\n')
gT.write('dursecond = 60 + tsecond - second'+'\n')
gT.write('else:'+'\n')
gT.write('dursecond = tsecond - second'+'\n')
gT.write(''+'\n')
gT.write('iftminute < minute:'+'\n')
gT.write('thour = thour - 1'+'\n')
gT.write('   
durminute = 60 + tminute - minute'+'\n')
gT.write('else:'+'\n')
gT.write('   
durminute = tminute - minute'+'\n')
gT.write(''+'\n')
gT.write('ifthour < hour:'+'\n')
gT.write('xday = 1'+'\n')
gT.write('durhour = hour - thour'+'\n')
gT.write('else:'+'\n')
gT.write('xday = 0'+'\n')
gT.write('durhour = thour - hour'+'\n')
gT.write(''+'\n')
gT.write('ifxday == 0:'+'\n')
gT.write('print "Generated Process Completed--", "start:", "%02d:%02d:%02d" 
% (ho

Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Torsten Bronger
Hallöchen!

D'Arcy J.M. Cain writes:

> On Fri, 02 May 2008 23:30:01 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
>
>> The OP was asking why people prefer on over the other. My answer
>> is that I prefer specifying "give me the default OS Python"
>> because anything not installed by the OS is to non-standardised
>> for me to worry about.
>
> [...]
>
> Certainly #! /usr/bin/python is fine if you never expect your
> software to run outside of your own little corner of the world but
> you asked why people prefer the env version and the answer is that
> we want to write software that runs everywhere that Python runs.

Granted, but you must draw the line somewhere anyway.  I cannot
pollute my program with hundreds of if clauses just to make it work
on every quirky system.  It's the *systems* where the streamlining
must happen, not the programs.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Ben Finney
Thorsten Kampe <[EMAIL PROTECTED]> writes:

> * Ben Finney (Fri, 02 May 2008 23:30:01 +1000)
> > The OP was asking why people prefer on over the other. My answer
> > is that I prefer specifying "give me the default OS Python"
> > because anything not installed by the OS is to non-standardised
> > for me to worry about.
> > 
> > Others may prefer something different, but then they get to wear
> > whatever problems occur as a result of that choice. I continue to
> > be bemused by that preference, and nothing that I've seen so far
> > in this thread illuminates the issue more.
> 
> You're missing the point. Apart from the really dubious terms you
> use ("OS installable package"), using env in the first line has
> exactly the effect to use the default path of Python (which is the
> first entry in your path)

No, because it's quite common for the PATH variable to have
'/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'.

If the system has a sysadmin-installed '/usr/local/bin/python'
installed as well as the OS-installed '/usr/bin/python', then the two
shebang options the OP raised will behave differently on such a
system. This seems to be quite the point of the discussion.

-- 
 \  "Time's fun when you're having flies."  -- Kermit the Frog |
  `\   |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Grant Edwards
On 2008-05-02, Ben Finney <[EMAIL PROTECTED]> wrote:

> The specified command takes the form of a fully-qualified file
> path, and zero or one arguments to the program. That command
> is then executed by the kernel, and the Python program file is
> passed as input to the resulting process.

Just to clarify that a bit a little, the name of the file (as
it was given to the "exec" system call) containing the "shebang
line" is passed to the resulting process as a command-line
parameter.

>> Why is one preferred over the other one ?
>
> I've never clearly understood why people want to use "#! /usr/bin/env
> python", which is prone to finding a different Python from the one
> installed by the operating system. I'd be interested to see what
> responses are in favour of it, and what the reasoning is.
>
> One possible reason is that the programmer is attempting to allow for
> systems where Python has been installed, but not from an operating
> system package.

Exactly.  the "env" approach works as long as python is
installed somewhere on the PATH.  "#!/usr/bin/python" will fail
if python is installed in /usr/local/bin/python.

-- 
Grant

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


Re: Do you know of a much simpler way of writing a program that writes a program?

2008-05-02 Thread Stefan Behnel
mcse jung wrote:
> Here is asample program that writes a program and then executes it.  
> Do you knowof a much simpler way of writing a program that writes a program?

I'm not quite sure what you are trying to achieve here, but I bet there is a
simpler way to do it than by generating a script. You might want to look into
functions.

http://docs.python.org/tut/node6.html#SECTION00660

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Ben Finney
Roy Smith <[EMAIL PROTECTED]> writes:

> In article <[EMAIL PROTECTED]>,
>  Ben Finney <[EMAIL PROTECTED]> wrote:
> 
> > Whereas if Python is *not* installed from an OS package, it's up
> > to the sys admin to ensure that it works -- not up to my program.
> > So I don't see the point in making it work by default, when what I
> > want for my program is that it works *with the default Python*,
> > not with some non-default installation.
> 
> Ben,
> 
> Have you ever shipped software to a customer?

Yes, and all parties have been quite happy with the results.

> Imagine the following conversation:
> 
> Customer: "Your product is broken. It says it can't find python, and
> I know I have it installed".
> 
> Vendor: "Where do you have it installed?"
> 
> Customer: "In /opt/bin/python"
> 
> Vendor: "Oh, that's your problem, it HAS to be in /usr/bin/python".

At this point the vendor isn't me, because this statement isn't true.
See below.

> Customer: "I can't install it there because  reason the customer has>. If you can't make your product work
> without requiring me to install python in /usr/bin, I'm afraid I
> can't buy your product".

At this point they have the simple option of running the program with
'python /path/to/the/program'. It's certainly not a case of "can't
make the product work".

It is, however, a case of "can't automatically account for every local
customisation sysadmins choose to make on their systems". Perfectly
willing to work with them to get their specific environment working,
but as a matter of simple economics it's not worth my time to attempt
to make such corner cases work automatically.

> If you want to hard-code /usr/bin/python into your application,
> that's your decision. If you would like to take on the task of
> convincing every sysadmin in the world to do things the way you
> think they should be done, have fun.

If they've already chosen to install Python to some unpredictable
location, they know what they're doing enough to invoke the program in
a specific way to get it working.

-- 
 \ Rommel: "Don't move, or I'll turn the key on this can of Spam!" |
  `\ -- The Goon Show, _Rommel's Treasure_ |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Ben Finney
"D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:

> On Fri, 02 May 2008 23:30:01 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
> > The OP was asking why people prefer on over the other. My answer
> > is that I prefer specifying "give me the default OS Python"
> > because anything not installed by the OS is [too] non-standardised
> > for me to worry about.
> 
> As someone else pointed out, not all the world is Linux.

It's a good thing I've never implied such to be the case.

-- 
 \ "If nature has made any one thing less susceptible than all |
  `\others of exclusive property, it is the action of the thinking |
_o__)   power called an idea"  -- Thomas Jefferson |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a list from a inconsistent text file

2008-05-02 Thread Mike Kent
On May 2, 9:47 am, Jetus <[EMAIL PROTECTED]> wrote:

> Hello Marc;
> Thanks for the input! I am worried about the comma in the "" data
> items, how do I tell Python to look for the "" data first, then use
> the comma separator?

Marc has already given you the correct answer.  You really should read
up on the csv module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Grant Edwards
On 2008-05-02, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]> wrote:

>>I've never clearly understood why people want to use "#! /usr/bin/env
>>python", which is prone to finding a different Python from the one
>>installed by the operating system. I'd be interested to see what
>>responses are in favour of it, and what the reasoning is.
>
> Simple, some systems are not as peculiar as a lot of Linux boxes which
> chug everything into /usr/bin, which is OS territory

On many Linux distros, Python is pretty much part of the OS.
Since the early days of RedHat, Python has been part of the
base/minimum install since a lot of the "required" system
utilities were written in python.  In Redhat, the package
manger was originally written in Python, so Python had to be in
"OS territory".

> (as has been decreed long ago by hier(7)), but rather use
> /usr/local/bin (all BSD Unix and derivatives) or /opt or
> whatever convention a particular operating system has.

In the Linux world, /usr/local/bin and /opt are for stuff
installed by the user, not stuff that is an integral, required
part of the OS distribution.

-- 
Grant

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


Re: portable fork+exec/spawn

2008-05-02 Thread Jean-Paul Calderone

On Fri, 02 May 2008 06:30:03 -0500, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

Brendan Miller <[EMAIL PROTECTED]> wrote:

 On Fri, 02 May 2008 13:25:55 +1000, Ben Finney wrote:

> URL:http://docs.python.org/lib/module-subprocess.html

 Awesome. This is exactly what I was hoping existed.


subprocess works well for spawn process, send input, receive output,
read exit code type jobs.

For jobs which require interactivity ie send input, receive output,
send input, receive output, ... it doesn't work well.  There isn't a
good cross platform solution for this yet.  pyexpect works well under
unix and is hopefully being ported to windows soon.


I haven't read all of this thread, so excuse me if this is out of place.

There is a good cross-platform solution, in fact.  It's Twisted's
spawnProcess API, which works on POSIX and Windows, supports supports
sending and receiving, and doesn't have deadlock issues since it's
event-driven.

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


Re: Getting started with pyvtk

2008-05-02 Thread Peter Pearson
On Thu, 01 May 2008 16:45:51 -0500, Robert Kern <[EMAIL PROTECTED]> wrote:
>
> pyvtk is not the Python interface to VTK. It is for the
> creation of VTK files.  The vtk(1) command is a Tcl shell
> with the VTK libraries loaded (I believe).  Read the VTK
> documentation for information on the Tcl interface if you
> really want to use it. 

You're right: I don't really want to use it.

> The Python interface is also included in the VTK sources,
> although it might not have been built on your machine. You
> have to enable it when you build VTK itself. The Python
> interface is essentially the same as the C++
> interface. There are Python examples in the VTK source
> tree.

That's the ticket: I don't want to "import pyvtk", I
want to "import vtk" and ape /usr/share/vtk/.../*.py.

Thanks.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a list from a inconsistent text file

2008-05-02 Thread Diez B. Roggisch

Jetus schrieb:

On May 2, 7:19 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

On Fri, 02 May 2008 04:14:47 -0700, Jetus wrote:

I have a comma delimited file that is separated by comma's, and then
sometimes by ","
c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211",
1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 "
c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211",
2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 "
c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211",
3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 "

The items are always delimited by commas but some items themselves contain
a comma and therefore are enclosed in double quotes.  So it's not
inconsistent.


How do I convert that line into a list?

Use the `csv` module in the standard library.

Ciao,
Marc 'BlackJack' Rintsch


Hello Marc;
Thanks for the input! I am worried about the comma in the "" data
items, how do I tell Python to look for the "" data first, then use
the comma separator?


As Marc said: use the CSV-module. It will ignore the comma inside 
""-surrounded fields. Then, once you extracted the columns, you might 
consider using the split-method on the columns to process further.


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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Grant Edwards
On 2008-05-02, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]> wrote:
> -On [20080502 07:51], Ben Finney ([EMAIL PROTECTED]) wrote:
>>To my mind, the Python interpreter installed by a package as
>>distributed with the OS *is* OS territory and belongs in /usr/bin/.
>
> That's the difference with a distribution, such as Linux, and full OSes ,
> such as BSDs or commercial Unix variants. They prefer to keep a pristine
> state for the OS vendor files

Python _is_ an OS vendor file in the Linux world.

> versus what the user can opt to install himself,

Traditionally, Python has not been optional.

> hence the /usr/bin - /usr/local/bin separation. Same for sbin,
> lib, and so on. It effectively guarantees you can nuke
> /usr/local without ill consequences for your OS.

That's the point. You _couldn't_ nuke Python and have your
system keep running.  That's why it was in /usr/bin.

-- 
Grant

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread D'Arcy J.M. Cain
On Fri, 02 May 2008 16:26:51 +0200
Torsten Bronger <[EMAIL PROTECTED]> wrote:
> > Certainly #! /usr/bin/python is fine if you never expect your
> > software to run outside of your own little corner of the world but
> > you asked why people prefer the env version and the answer is that
> > we want to write software that runs everywhere that Python runs.
> 
> Granted, but you must draw the line somewhere anyway.  I cannot

No one is talking about if statements here.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finally had to plonk google gorups.

2008-05-02 Thread Michael Torrie
Shawn Milochik wrote:
> How does one "plonk" stuff from Google Groups? Specifically, how
> can this be done in Gmail?

Set up a filter that looks for some phrase in the mail headers that
identifies messages originating from google groups.  Gmail's filters are
fairly flexible.  I'd probably just have it look for certain words.
Look at an e-mail's source (raw view) and particularly check in the
headers for things to filter by.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cookie Confusion - How to Set a Cookie

2008-05-02 Thread Aaron Watters
On May 1, 9:02 am, [EMAIL PROTECTED] wrote:
> On Apr 29, 3:35 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
>
>
>
> > > Thanks for the code, Aaron.  I will give it a try.
>
> > > I've been reading some more about cookielib and am not sure whether I
> > > should use Cookie or cookielib.  This is what I want to do:  a user is
> > > going to login.  Upon a successful login, I want to write their name
> > > and date/time of visit to a cookie file. Which is the correct python
> > > module to use?
>
> > Cookie does parsing and generation of cookie strings
> > for server-side applications like your CGI script.
>
> > The cookielib module
> > is designed for either implementing a client like a web browser
> > or emulating a client/browser (for web scraping, for example).
>
> > I think you want to use Cookie.
> > The distinction could be made clearer in
> > the docs, imho.
>
> > Also, when you say "write the cookie file" I think you mean
> > "store the cookie to the client browser".  This should happen
> > automatically when you send the cookie header to the client
> > correctly (if the client is configured to cooperate).
>
> >   -- Aaron Watters
>
> > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=default+does+n...
>
> Sorry for the slow replies.  I've been in & out with a sick child.
>
> I'm used to my javascript cookies.  They are automatically written to
> a cookie.txt file in a .mozilla dir under my user.  When I say to
> 'write the cookie file' this is what I was referring to.  I was
> expecting my python cookie to automatically get written to the same
> file.  I have't seen this happen yet.

Hmmm.  I don't know how cookies are stored on the client.
I recommend using the standard cgi debug
environment dump after setting
a cookie to see if the cookie is coming back to the server.
If it is not something is wrong -- you are setting it incorrectly,
or the server or client is blocking the cookie.

Note if you are testing on one machine: some browsers
and servers have by default
special security restrictions on
"localhost" loopbacks -- it may be that this is causing
either the server or the client to ignore the cookie.

  -- Aaron Watters
===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=cooked
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Torsten Bronger
Hallöchen!

D'Arcy J.M. Cain writes:

> On Fri, 02 May 2008 16:26:51 +0200
> Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
>>> Certainly #! /usr/bin/python is fine if you never expect your
>>> software to run outside of your own little corner of the world
>>> but you asked why people prefer the env version and the answer
>>> is that we want to write software that runs everywhere that
>>> Python runs.
>> 
>> Granted, but you must draw the line somewhere anyway.  I cannot
>
> No one is talking about if statements here.

Sorry to become laconical, but your reply was so, too:
http://en.wikipedia.org/wiki/Abstraction

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread D'Arcy J.M. Cain
On Sat, 03 May 2008 00:44:00 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:
> > As someone else pointed out, not all the world is Linux.
> 
> It's a good thing I've never implied such to be the case.

You haven't *said* it but you have definitely *implied* it.  Installing
Python in /usr/bin is not common.  It is very specific to your system.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread D'Arcy J.M. Cain
On Sat, 03 May 2008 00:43:02 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> Roy Smith <[EMAIL PROTECTED]> writes:
> > Have you ever shipped software to a customer?
> 
> Yes, and all parties have been quite happy with the results.

When some of us talk about shipping software we aren't talking about a
20 line script delivered to our uncle's construction company office.  We
are talking about millions of lines of code in thousands of programs and
modules that has to run out of the box on whatever system the client
happens to run on.

> > Customer: "I can't install it there because  > reason the customer has>. If you can't make your product work
> > without requiring me to install python in /usr/bin, I'm afraid I
> > can't buy your product".
> 
> At this point they have the simple option of running the program with
> 'python /path/to/the/program'. It's certainly not a case of "can't
> make the product work".

Simple for your 20 line single script.  Not so simple for my million
line, integrated system that has to work everywhere.

> It is, however, a case of "can't automatically account for every local
> customisation sysadmins choose to make on their systems". Perfectly
> willing to work with them to get their specific environment working,
> but as a matter of simple economics it's not worth my time to attempt
> to make such corner cases work automatically.

If by "corner case" you mean "some system that I don't personally run"
then OK but to some of us your system is the corner case and we would
like our code to run there as well.

Real software has to deal with the fact that support costs money.
You may be able to deal with one or two clients that way but that does
not scale very well.

> If they've already chosen to install Python to some unpredictable
> location, they know what they're doing enough to invoke the program in
> a specific way to get it working.

Unpredictable to you.  Perfectly predictable on their system.

I do believe I am done with this thread.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: no cleanup on TERM signal

2008-05-02 Thread Laszlo Nagy



You can replace the try/finally code with a "with resource:
do_something()" block if the object supporst the context manager protocol.
  

I'm using 2.4 so...

If you want to run some code during the shutdown phase of the Python
process you can register a callback function in the "atexit" module.
  
I also wanted to tell this to the OP but he was asking about signals. 
AFAIK atexit is only called on SIGTERM, not on others.

Do NOT mix threads and signals. It's usually a very bad idea and may
lead to surprising side effects. Signals are only handled by the main
thread.
  

Well, I have to, because:

#1. I have a server that uses threads. Using fork() instead of threading 
would be a nightmare in my case.
#2. It must support signals, just because some users tend to use things 
like "killall python" and try/finally is not useful in those cases. I 
cannot do anything to prevent the users killing the server. They will 
just do it...


I know that signals are handled in the main thread only. This is why I'm 
using a threading.Event() object to allow all threads shut down 
cooperatively: sigterm will set the event, and then all threads 
(including the main thread) will exit gracefully (within a given 
timeout). Do you know a better solution?


Thanks,

  Laszlo

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Grant Edwards
On 2008-05-02, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
> On Sat, 03 May 2008 00:44:00 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
>> "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:
>> > As someone else pointed out, not all the world is Linux.
>> 
>> It's a good thing I've never implied such to be the case.
>
> You haven't *said* it but you have definitely *implied* it.
> Installing Python in /usr/bin is not common.

It is common.  That's where it's installed by almost all Linux
distributions.

> It is very specific to your system.

Are you claiming that Linux is not a "common" Unix-like OS?

-- 
Grant

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


Re: help with list comprehension

2008-05-02 Thread Yves Dorfsman

George Sakkis wrote:


Another alternative is:

from operator import itemgetter

def m3():
colours, nums = zip(*map(itemgetter('colour','num'), l))

It's slower than m1() but faster than m2(); it's also the most
concise, especially if you extract more than two keys.


Good you guys gave me some ideas, I've made m3() work:

def m3()
  total = [ [e['colour'], e['num'], e['couleur']] for e in l ]
  c,d,e = zip(*total)
  return map(list, [c,d,e])

(I have to transform to lists, I need to transform them later on, so tuples 
won't work).


Unfortunately the timing is inconsistant, the first time I run
python -m timeit 'import listcomp ; listcomp.m1()'

m1 is the fastest. But then if I run the test several times, they all seem 
to be about the same time ; I'll have to try with a large list.


Now here is a question:
Is there any way to change my first line there for the list comp. to return 
a list of lists rather than a list of tuples ?

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


Re: Getting started with pyvtk

2008-05-02 Thread Paul Melis

Peter Pearson wrote:

On Thu, 01 May 2008 16:45:51 -0500, Robert Kern <[EMAIL PROTECTED]> wrote:

pyvtk is not the Python interface to VTK. It is for the
creation of VTK files.  The vtk(1) command is a Tcl shell
with the VTK libraries loaded (I believe).  Read the VTK
documentation for information on the Tcl interface if you
really want to use it. 


You're right: I don't really want to use it.


The Python interface is also included in the VTK sources,
although it might not have been built on your machine. You
have to enable it when you build VTK itself. The Python
interface is essentially the same as the C++
interface. There are Python examples in the VTK source
tree.


That's the ticket: I don't want to "import pyvtk", I
want to "import vtk" and ape /usr/share/vtk/.../*.py.

Thanks.


I'm not sure you've been helped so far as you seem to already understand 
about pyvtk not being the official VTK bindings :)


So, what would you like to know?

Paul

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


pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread globalrev
if pygame.key.get_pressed[K_a]:
print "Muppet"

K_a is not defined.


but yes it is. why do i get this error?

this works:
if pygame.key.get_pressed():
print "donkey"
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Yves Dorfsman

Thanks everybody, I didn't mean to start a flamewar...
I do get it now, it's whatever python is in the path, vs. the specific one 
you're pointing to.


Ben Finney wrote:



No, because it's quite common for the PATH variable to have
'/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'.

If the system has a sysadmin-installed '/usr/local/bin/python'
installed as well as the OS-installed '/usr/bin/python', then the two
shebang options the OP raised will behave differently on such a
system. This seems to be quite the point of the discussion.



And I have to admit, I prefer specifying the version (full path) because I 
have run into too many problem when users have different PATHs and end up 
running different version of an interpreter.


Yves.
--
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread Diez B. Roggisch

globalrev schrieb:

if pygame.key.get_pressed[K_a]:
print "Muppet"

K_a is not defined.


but yes it is. why do i get this error?


No it isn't - otherwise you wouldn't get this error, wouldn't you?

What IS defined is

pygame.K_a

Or if you do

from pygame import K_a

then K_a is defined as well.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-02 Thread Gabriel Genellina
En Thu, 01 May 2008 10:30:03 -0300, Nick Craig-Wood <[EMAIL PROTECTED]>  
escribió:



As for where to store it, I use os.path.expanduser("~") to find the
base directory and a bit of platform specific code.

Something like this snippet

self.is_windows = sys.platform == 'win32'
self.home = os.path.expanduser("~")
if self.is_windows:
self.config_dir = os.path.join(self.home, "Application Data",  
self.NAME)

else:
self.config_dir = os.path.join(self.home, "."+self.NAME)
if not os.path.isdir(self.config_dir):
os.makedirs(self.config_dir, mode=0700)
self.config_file = os.path.join(self.config_dir, "config")


Please don't do that if you distribute your programs. "Application Data"  
is a localized name, like "Program Files" and all special folders. On my  
Spanish version of Windows, they're "Datos de programa" y "Archivos de  
Programa" respectively, and the user may choose to move them to another  
location.
Use SHGetFolderPath to obtain the path; see  
http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx


--
Gabriel Genellina

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


Re: Python 2.6 and wrapping C libraries on Windows

2008-05-02 Thread Gabriel Genellina
En Thu, 01 May 2008 09:09:21 -0300, Christian Heimes <[EMAIL PROTECTED]>  
escribió:



illume schrieb:

Has anyone tested the new python binaries that link to msvcr90.dll on
win9x machines?


It doesn't matter to use because Python 2.6 and 3.0 require at least
Windows 2000 SP4. The 9x, ME and NT series aren't supported any more.


That should be menctioned in the What's new? document - I could not find  
any reference.


--
Gabriel Genellina

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


Re: pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread globalrev
On 2 Maj, 18:13, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> globalrev schrieb:
>
> > if pygame.key.get_pressed[K_a]:
> > print "Muppet"
>
> > K_a is not defined.
>
> > but yes it is. why do i get this error?
>
> No it isn't - otherwise you wouldn't get this error, wouldn't you?
>
> What IS defined is
>
> pygame.K_a
>
> Or if you do
>
> from pygame import K_a
>
> then K_a is defined as well.
>
> Diez

ok thanks
if (key.get_pressed[K_t] and key.get_pressed[K_f]):
 print "Yup!"

said int he tut it confused me.


anyway i changed it and the list or dict from keygetpressed is all
zeros but the K_a always is true whether i push it or not.




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


Preventing 'bad' filenames from raising errors in os.path

2008-05-02 Thread python
Bad file names, i.e. filenames the OS considers illegal, will cause
functions in the os.path module to raise an error.

Example:

import os.path
print os.path.getsize( 'c:/pytest/*.py' )

On Windows XP using Python 2.5.2 I get the following traceback:

Traceback (most recent call last):
  File "", line 74, in run_nodebug
  File "", line 3, in 
  File "C:\Python\lib\ntpath.py", line 228, in getsize
return os.stat(filename).st_size
WindowsError: [Error 123] The filename, directory name, or volume label
syntax is incorrect: 'c:/pytest/*.py'

Since there are many places a user can enter a path name (interactively,
via config files, etc) in most applications, is there an os sensitive
function that can be used to detect bad file names?

As a matter of best practice, how do you wrap your use of file and path
names to prevent unexpected failures? (There has to be a better
alternative than try/except blocks around each use of an os.path
function in one's code?)

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-02 Thread Carl Banks
On May 2, 12:30 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 01 May 2008 10:30:03 -0300, Nick Craig-Wood <[EMAIL PROTECTED]>
> escribió:
>
> > As for where to store it, I use os.path.expanduser("~") to find the
> > base directory and a bit of platform specific code.
>
> > Something like this snippet
>
> > self.is_windows = sys.platform == 'win32'
> > self.home = os.path.expanduser("~")
> > if self.is_windows:
> > self.config_dir = os.path.join(self.home, "Application Data",
> > self.NAME)
> > else:
> > self.config_dir = os.path.join(self.home, "."+self.NAME)
> > if not os.path.isdir(self.config_dir):
> > os.makedirs(self.config_dir, mode=0700)
> > self.config_file = os.path.join(self.config_dir, "config")
>
> Please don't do that if you distribute your programs. "Application Data"
> is a localized name, like "Program Files" and all special folders. On my
> Spanish version of Windows, they're "Datos de programa" y "Archivos de
> Programa" respectively, and the user may choose to move them to another
> location.
> Use SHGetFolderPath to obtain the path; see  
> http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx

Thanks for the heads up: wasn't aware those guys were localized.

(Though I wonder why they bothered: Microsoft gives typical users a
guilt trip for putting their own files anywhere other than My
Documents, or Mis Documentos, or whatever.)


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


Re: pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread globalrev
print pygame.K_a displays 97 btw. what does that mean? i though it
would return true or false or 0 or 1.
--
http://mail.python.org/mailman/listinfo/python-list


Non-blocking connect

2008-05-02 Thread mp
Code is at bottom. Basically, if I turn off socket blocking prior to
connecting, I get a "Socket is not connected" error when I try to send
data. However, if I do not turn off blocking, OR if I place a print
statement anywhere before the send call, it works! WTF?

I'd like to understand what's going on in the background here, if you
know don't skimp on the details.

Thanks

---
import
socket
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.setblocking(0)
sock.connect_ex(('localhost',
9000))
sock.setblocking(1)
sock.send('foo')
sock.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finally had to plonk google gorups.

2008-05-02 Thread Mensanator
On May 2, 9:53 am, Michael Torrie <[EMAIL PROTECTED]> wrote:
> Shawn Milochik wrote:
> > How does one "plonk" stuff from Google Groups? Specifically, how
> > can this be done in Gmail?
>
> Set up a filter that looks for some phrase in the mail headers that
> identifies messages originating from google groups.  Gmail's filters are
> fairly flexible.  I'd probably just have it look for certain words.
> Look at an e-mail's source (raw view) and particularly check in the
> headers for things to filter by.

Why don't you just block all messages from Gmail?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing 'bad' filenames from raising errors in os.path

2008-05-02 Thread Matimus
On May 2, 9:40 am, [EMAIL PROTECTED] wrote:
> Bad file names, i.e. filenames the OS considers illegal, will cause
> functions in the os.path module to raise an error.
>
> Example:
>
> import os.path
> print os.path.getsize( 'c:/pytest/*.py' )
>
> On Windows XP using Python 2.5.2 I get the following traceback:
>
> Traceback (most recent call last):
>   File "", line 74, in run_nodebug
>   File "", line 3, in 
>   File "C:\Python\lib\ntpath.py", line 228, in getsize
> return os.stat(filename).st_size
> WindowsError: [Error 123] The filename, directory name, or volume label
> syntax is incorrect: 'c:/pytest/*.py'
>
> Since there are many places a user can enter a path name (interactively,
> via config files, etc) in most applications, is there an os sensitive
> function that can be used to detect bad file names?
>
> As a matter of best practice, how do you wrap your use of file and path
> names to prevent unexpected failures? (There has to be a better
> alternative than try/except blocks around each use of an os.path
> function in one's code?)
>
> Thanks,
> Malcolm

What do you find troubling about try/except?

Compare:

import os.path

path = raw_input("enter a path:")
if isvalidpath(path): # this is a made up name
print os.path.getsize(path)
else:
# Do something else

To:

import os.path

path = raw_input("enter a path:")
try:
print os.path.getsize(path)
except WindowsError:
# Do something else

Now, I can understand if you don't like the "WindowsError" as that is
obviously platform specific. The try/except pattern however is the way
errors are handled in python and the best and most appropriate way to
deal with it. The above example just shows that at the very least
there isn't a significant difference in code size between the two
methods.

I don't know what the equivalent error is called in *nix but assume it
is PosixError (it isn't), then it would just be written this way:

import os.path

path = raw_input("enter a path:")
try:
print os.path.getsize(path)
except (WindowsError, PosixError):
# Do something else


You don't _always_ need to wrap os.path functions with try/except. You
only need to wrap where there is reason to expect that the input might
be prone to error. In those cases the alternative is what? wrapping it
in a if/else instead? How is that better?

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


Re: Pyserial - send and receive characters through linux serial port

2008-05-02 Thread terry
On Apr 26, 8:21 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-04-25, terry <[EMAIL PROTECTED]> wrote:
>
> > I am trying to send a character to '/dev/ttyS0' and expect the
> > same character and upon receipt I want to send another
> > character. I tired withPyserialbut in vain.
>
> Pyserialworks.  I've been using it almost daily for many
> years.  Either your program is broken, your serial port is
> broken, or the device connected to the serial port is broken.
>
> > Test Set up:
>
> > 1. Send '%' to serial port and make sure it reached the serial port.
> > 2. Once confirmed, send another character.
>
> > I tried with write and read methods inPyserialbut no luck.
>
> > Can you help?
>
> Ah yes, the problem is in line 89 of your program.
>
> We've no way to help if you don't provide details. If you
> really want help, write as small a program as possible that
> exhibits the problem.  I'd like to emphasize _small_. The
> larger the program the less likely people are to look at it,
> and the less likely they are to find the problem if they do
> look at it.
>
> Much of the time the exercise of writing a small demo program
> will lead you to the answer.  If not, then post it, along with
> the output from the program that shows the problem.
>
> Then we can tell you what you did wrong.
>
> --
> Grant Edwards                   grante             Yow! I'm also against
>                                   at               BODY-SURFING!!
>                                visi.com            

Here is the code.

"""Open serial connection"""
def openSerialConnection(self,serpt):
try:
s1 = serial.Serial(serpt,timeout=10)

except:
self.print_u("Failed to open serial port %s. " %serpt)

def enterThroughSerialPort(self,serpt):
s1 = serial.Serial(serpt,timeout=10)
 self.print_u('Sending ..')
 while True:
s1.write('*')
   c = s1.read(1)
   if c:
  self.print_u('Found "*" ')
break
print c
 s1.write('enter\r')
 s1.read('login')

if __name__ == '__main__':
serpt = '/dev/ttyS0'
x.openSerialConnection(serpt)
# funtion to reboot the device goes here ---#
x.enterThroughSerialPort(serpt)

After opening the serial connection, the device is rebooted followed
by sending '*' to serial port and reading back the same. I seem to
have problem while trying to read '*' back from serial port. First of
all I am not sure if serial port received the '*'.

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


Re: pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread Patrick Mullen
The K_a is a constant integer, but you don't need to worry about it's
value.  It tells you the index in get_pressed() to check for.  So:

print pygame.key.get_pressed()[pygame.K_a]

Says, look at the 97th index in the get_pressed() list and see if that is a
1 or a 0.

Or if you use the pygame events:

for evt in pygame.event.get():
if evt.type == pygame.KEYDOWN and evt.key == pygame.K_a:
print "a pressed"

evt.type and evt.key will both be integers that map to one of the type
constants and one of the key constants respectively.  This way the key
constant works in both types of input handling (which are both useful for
different types of input).
--
http://mail.python.org/mailman/listinfo/python-list

Re: pygame.key.get_pressed[K_a], K_a is not defined!?

2008-05-02 Thread Mike Driscoll
On May 2, 12:03 pm, globalrev <[EMAIL PROTECTED]> wrote:
> print pygame.K_a displays 97 btw. what does that mean? i though it
> would return true or false or 0 or 1.

That's probably the key code value. Or the ASCII representation for
the key. You'd have to read the pygame docs to really know.

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


Re: Preventing 'bad' filenames from raising errors in os.path

2008-05-02 Thread Martin v. Löwis
> Now, I can understand if you don't like the "WindowsError" as that is
> obviously platform specific. The try/except pattern however is the way
> errors are handled in python and the best and most appropriate way to
> deal with it. The above example just shows that at the very least
> there isn't a significant difference in code size between the two
> methods.
> 
> I don't know what the equivalent error is called in *nix but assume it
> is PosixError (it isn't)

The common base class to use here is actually OSError. WindowsError is
a subclass thereof.

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Thorsten Kampe
* Ben Finney (Sat, 03 May 2008 00:37:45 +1000)
> Thorsten Kampe <[EMAIL PROTECTED]> writes:
> > * Ben Finney (Fri, 02 May 2008 23:30:01 +1000)
> > > The OP was asking why people prefer on over the other. My answer
> > > is that I prefer specifying "give me the default OS Python"
> > > because anything not installed by the OS is to non-standardised
> > > for me to worry about.
> > > 
> > > Others may prefer something different, but then they get to wear
> > > whatever problems occur as a result of that choice. I continue to
> > > be bemused by that preference, and nothing that I've seen so far
> > > in this thread illuminates the issue more.
> > 
> > You're missing the point. Apart from the really dubious terms you
> > use ("OS installable package"), using env in the first line has
> > exactly the effect to use the default path of Python (which is the
> > first entry in your path)
> 
> No, because it's quite common for the PATH variable to have
> '/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'.
> 
> If the system has a sysadmin-installed '/usr/local/bin/python'
> installed as well as the OS-installed '/usr/bin/python', then the two
> shebang options the OP raised will behave differently on such a
> system. This seems to be quite the point of the discussion.

Again you're missing the point. If you or whoever installs Python (or 
another version of Python) to /usr/local/bin and puts this in the path 
to front (as it's often done) then /you/ want that Python to be the 
"default" one. It would just be silly to say "no, I the developer want 
/usr/bin/python".

So in general "#! env" is better while in certain circumstance 
hardcoding the path to /usr/bin/python can be better.


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


Re: Non-blocking connect

2008-05-02 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 mp <[EMAIL PROTECTED]> wrote:

> Code is at bottom. Basically, if I turn off socket blocking prior to
> connecting, I get a "Socket is not connected" error when I try to send
> data. However, if I do not turn off blocking, OR if I place a print
> statement anywhere before the send call, it works! WTF?
> 
> I'd like to understand what's going on in the background here, if you
> know don't skimp on the details.
> 
> Thanks
> 
> ---
> import
> socket
> sock = socket.socket(socket.AF_INET,
> socket.SOCK_STREAM)
> sock.setblocking(0)
> sock.connect_ex(('localhost',
> 9000))
> sock.setblocking(1)
> sock.send('foo')
> sock.close()

I can't be 100% sure about this because I don't know what's running on your 
port 9000 that you're trying to connect to, but I think I know what's going 
on.

I just tried your code, but changed 9000 to 22 (ssh).  What I found is that 
if you eliminate the setblocking(0) call, the connect_ex() call returns 0, 
indicating it succeeded.  If you leave the setblocking(0) call in, 
connect_ex() returns EINPROGRESS (Operation now in progress).  This makes 
sense.  Here's the code:

import socket
import os
import errno

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
err = sock.connect_ex(('localhost', 22))
print errno.errorcode[err], os.strerror(err)

When you do a TCP connect, there is what's called a three-way handshake 
that happens between the TCP stacks at the two ends of the connection.  I 
send a packet with the SYN bit set, you respond with a packet with both SYN 
and ACK set, and I respond with an ACK.  Even when both ends are on the 
same box (i.e. localhost), this has to happen.

Quoting from http://docs.python.org/lib/socket-objects.html:

> Some notes on socket blocking and timeouts: [...] In non-blocking mode, 
> operations fail (with an error that is unfortunately system-dependent) if 
> they cannot be completed immediately.

Since the three-way handshake can't be completed immediately, the 
connect_ex call fails when you try it in non-blocking mode.

So, that's the explanation.  Now the question: What are you trying to do 
that you need non-blocking mode?  Or are you just experimenting to see what 
happens?

BTW, this was done on an OSX-10.5.2 box, but I think the result would be 
essentially the same on any platform.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Carl Banks
On May 2, 11:07 am, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> On Sat, 03 May 2008 00:43:02 +1000
>
> Ben Finney <[EMAIL PROTECTED]> wrote:
> > Roy Smith <[EMAIL PROTECTED]> writes:
> > > Have you ever shipped software to a customer?
>
> > Yes, and all parties have been quite happy with the results.
>
> When some of us talk about shipping software we aren't talking about a
> 20 line script delivered to our uncle's construction company office.  We
> are talking about millions of lines of code in thousands of programs and
> modules that has to run out of the box on whatever system the client
> happens to run on.

If you're shipping a program that large you out to be packaging the
Python interpreter with it.

Frankly, this whole discussion is silly, as if it's some kind hard
thing to open the script with a text editor and modify the shbang
line.


Carl Banks



> > > Customer: "I can't install it there because  > > reason the customer has>. If you can't make your product work
> > > without requiring me to install python in /usr/bin, I'm afraid I
> > > can't buy your product".
>
> > At this point they have the simple option of running the program with
> > 'python /path/to/the/program'. It's certainly not a case of "can't
> > make the product work".
>
> Simple for your 20 line single script.  Not so simple for my million
> line, integrated system that has to work everywhere.
>
> > It is, however, a case of "can't automatically account for every local
> > customisation sysadmins choose to make on their systems". Perfectly
> > willing to work with them to get their specific environment working,
> > but as a matter of simple economics it's not worth my time to attempt
> > to make such corner cases work automatically.
>
> If by "corner case" you mean "some system that I don't personally run"
> then OK but to some of us your system is the corner case and we would
> like our code to run there as well.
>
> Real software has to deal with the fact that support costs money.
> You may be able to deal with one or two clients that way but that does
> not scale very well.
>
> > If they've already chosen to install Python to some unpredictable
> > location, they know what they're doing enough to invoke the program in
> > a specific way to get it working.
>
> Unpredictable to you.  Perfectly predictable on their system.
>
> I do believe I am done with this thread.
>
> --
> D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three 
> wolveshttp://www.druid.net/darcy/   |  and a sheep voting on
> +1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.

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


Re: Finally had to plonk google gorups.

2008-05-02 Thread Michael Torrie
Mensanator wrote:
> On May 2, 9:53 am, Michael Torrie <[EMAIL PROTECTED]> wrote:
>> Shawn Milochik wrote:
>>> How does one "plonk" stuff from Google Groups? Specifically, how
>>> can this be done in Gmail?
>> Set up a filter that looks for some phrase in the mail headers that
>> identifies messages originating from google groups.  Gmail's filters are
>> fairly flexible.  I'd probably just have it look for certain words.
>> Look at an e-mail's source (raw view) and particularly check in the
>> headers for things to filter by.
> 
> Why don't you just block all messages from Gmail?

Brilliant!  Seeing as he's asking about doing the filtering in Gmail
(implying it's use for his own posting and viewing the list) that would
work splendidly for him!  Or not.

Of course you're not likely to see this message either since I and many
folks on here post from gmail.

Spam comes mainly from Google Groups, not as much from Gmail in my
experience.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SSL through python. possible ?

2008-05-02 Thread Heikki Toivonen
Mike Driscoll wrote:
> On Apr 29, 8:56 am, TkNeo <[EMAIL PROTECTED]> wrote:
>> I need to do SSL file transfer using python? Is there a library i can
>> use ?
> 
> http://sandbox.rulemaker.net/ngps/m2/

M2Crypto has since moved to http://chandlerproject.org/Projects/MeTooCrypto

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


Re: Non-blocking connect

2008-05-02 Thread mp
Thanks Roy. I was just trying to understand someone else's code, but
in the end it turns out that this was just a bug.

What weirded me out was how injecting a print statement preventing the
error from occurring, but now I get it. Without blocking, the
connection handshake occurs in parallel after the connect_exc method
is called. In my example, my processor reaches the send call before
the connection manages to complete in the background. However, if you
stick in a print statement after the connect_exc call and before the
send call, it delays processing just long enough for the connection to
complete, thus no exception is thrown by the send call.
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling variable function name ?

2008-05-02 Thread TkNeo
On Apr 30, 11:05 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> TkNeo<[EMAIL PROTECTED]> writes:
>
> > George - Thanks for your reply but what you suggested is not working:
>
> > def FA(param1,param2):
> > print "FA" + param1 + " " + param2
> > def FA(param1,param2):
> > print "FB" + param1 + " " + param2
> > def FA(param1,param2):
> > print "FC" + param1 + " " + param2
>
> > temp = sys.argv[1]
>
> > func = globals()["F" + temp]
> > func("Hello", "World")
>
> > I ran the script with first parameter as B and i get the following
> > message
> > KeyError: 'FB'
>
> Perhaps if you call your three function FA, FB, FC instead of FA, FA,
> FA it'll help?
>
> --
> Arnaud

oh crap. I can't believe I was doing that ! :) Thanks for pointing
out. works perfect.

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


Re: is +=1 thread safe

2008-05-02 Thread Arnaud Delobelle
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:

>
> There are no modern processors with an opcode for incrementing a memory
> location!?  At least my C64 can do that.  ;-)

Indeed!  I remember a simple use was to make the border change colour
very fast, a v. cool effect when you're 12!
 
CLV
LOOP:   INC $D020
BVC LOOP

(from memory, untested!)

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


list.index crashes when the element is not found

2008-05-02 Thread TkNeo
WHAT ?

This is crazy
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-02 Thread Erik Max Francis

Ben Finney wrote:


No, because it's quite common for the PATH variable to have
'/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'.

If the system has a sysadmin-installed '/usr/local/bin/python'
installed as well as the OS-installed '/usr/bin/python', then the two
shebang options the OP raised will behave differently on such a
system. This seems to be quite the point of the discussion.


Yes, and that's the reason the env form is preferred.  If someone -- 
either the system administrator, or the user environment, or the person 
executing the program on the fly -- has changed the PATH, they did it 
for a reason.  If /usr/local/bin is in the PATH before /usr/bin, then 
that is a deliberate choice (whether system-wide or not) to prefer 
executables in /usr/local/bin to those in /usr/bin, and that is being 
done for a very conscious reason.  Which is why the PATH exists in the 
first place, and why invoking the script with env is preferable.



--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do you know of a much simpler way of writing a program that writes a program?

2008-05-02 Thread Erik Max Francis

mcse jung wrote:

Here is asample program that writes a program and then executes it.  
Do you knowof a much simpler way of writing a program that writes a program?


It looks like you have a program which is more printed text than program 
logic.  In which case, the usual solution is to use a templating system, 
where most of the text is unmodified and you only set out the specific 
areas where you want to insert logic.


EmPy is one:

http://www.alcyone.com/software/empy/

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non-blocking connect

2008-05-02 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 mp <[EMAIL PROTECTED]> wrote:

> Thanks Roy. I was just trying to understand someone else's code, but
> in the end it turns out that this was just a bug.
> 
> What weirded me out was how injecting a print statement preventing the
> error from occurring, but now I get it. Without blocking, the
> connection handshake occurs in parallel after the connect_exc method
> is called. In my example, my processor reaches the send call before
> the connection manages to complete in the background. However, if you
> stick in a print statement after the connect_exc call and before the
> send call, it delays processing just long enough for the connection to
> complete, thus no exception is thrown by the send call.

I don't really understand that last part.  There shouldn't be any 
background processing going on, unless there's a lot more code than you 
showed.

The three-way handshake *can't* happen in the background, because 
connect_ex() has no way to know what value to return until the handshake is 
completed.  Let's say I send a SYN, and 15 seconds later, you send a RST 
(indicating that the connection has been refused).  The connect_ex() call 
has to have waited the 15 seconds for this to happen so it knows to return 
an appropriate error code.

I do not understand why sticking a print statement in there should make any 
difference.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SSL through python. possible ?

2008-05-02 Thread Giampaolo Rodola'
On 29 Apr, 15:56, TkNeo <[EMAIL PROTECTED]> wrote:
> I need to do SSL file transfer using python? Is there a library i can
> use ?
>
> Thanks.

If you have patience you can wait for Python 2.6 which will include a
new ssl module, otherwise there are a lot of third party libraries out
there which already binds OpenSSL for Python.


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pyserial - send and receive characters through linux serial port

2008-05-02 Thread terry
On May 2, 10:26 am, terry <[EMAIL PROTECTED]> wrote:
> On Apr 26, 8:21 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On 2008-04-25, terry <[EMAIL PROTECTED]> wrote:
>
> > > I am trying to send a character to '/dev/ttyS0' and expect the
> > > same character and upon receipt I want to send another
> > > character. I tired withPyserialbut in vain.
>
> > Pyserialworks.  I've been using it almost daily for many
> > years.  Either your program is broken, your serial port is
> > broken, or the device connected to the serial port is broken.
>
> > > Test Set up:
>
> > > 1. Send '%' to serial port and make sure it reached the serial port.
> > > 2. Once confirmed, send another character.
>
> > > I tried with write and read methods inPyserialbut no luck.
>
> > > Can you help?
>
> > Ah yes, the problem is in line 89 of your program.
>
> > We've no way to help if you don't provide details. If you
> > really want help, write as small a program as possible that
> > exhibits the problem.  I'd like to emphasize _small_. The
> > larger the program the less likely people are to look at it,
> > and the less likely they are to find the problem if they do
> > look at it.
>
> > Much of the time the exercise of writing a small demo program
> > will lead you to the answer.  If not, then post it, along with
> > the output from the program that shows the problem.
>
> > Then we can tell you what you did wrong.
>
> > --
> > Grant Edwards                   grante             Yow! I'm also against
> >                                   at               BODY-SURFING!!
> >                                visi.com            
>
> Here is the code.
>
> """Open serial connection"""
>         def openSerialConnection(self,serpt):
>             try:
>                 s1 = serial.Serial(serpt,timeout=10)
>
>             except:
>                 self.print_u("Failed to open serial port %s. " %serpt)
>
>         def enterThroughSerialPort(self,serpt):
>             s1 = serial.Serial(serpt,timeout=10)
>              self.print_u('Sending ..')
>              while True:
>                 s1.write('*')
>                c = s1.read(1)
>                if c:
>                   self.print_u('Found "*" ')
>                     break
>             print c
>              s1.write('enter\r')
>              s1.read('login')
>
> if __name__ == '__main__':
>     serpt = '/dev/ttyS0'
>     x.openSerialConnection(serpt)
>     # funtion to reboot the device goes here ---#
>     x.enterThroughSerialPort(serpt)
>
> After opening the serial connection, the device is rebooted followed
> by sending '*' to serial port and reading back the same. I seem to
> have problem while trying to read '*' back from serial port. First of
> all I am not sure if serial port received the '*'.
>
> Thanks!- Hide quoted text -
>
> - Show quoted text -

This is the err message I received:

c = s1.read(1)
File "/usr/local/lib/python2.5/site-packages/serial/serialposix.py",
line 275, in read
ready,_,_ = select.select([self.fd],[],[], self._timeout)
--
http://mail.python.org/mailman/listinfo/python-list


Re: i want to add a timeout to my code

2008-05-02 Thread Gabriel Genellina
En Thu, 01 May 2008 17:06:20 -0300, maehhheeyy <[EMAIL PROTECTED]>  
escribió:

On Apr 29, 3:29 pm, John Krukoff <[EMAIL PROTECTED]> wrote:

On Tue, 2008-04-29 at 14:47 -0700, maehhheeyy wrote:
> On Apr 17, 4:24 pm, Miki <[EMAIL PROTECTED]> wrote:
> > On Apr 17, 1:10 pm,maehhheeyy<[EMAIL PROTECTED]> wrote:

> > > I want to add a timeout so that when I pull out my gps from my  
serial
> > > port, it would wait for a bit then loop and then see if it's  
there. I
> > > also want to add a print statement saying that there is no GPS  
device
> > > found. However when I run my code and unplug my serial port, my  
code

> > > will just hang until I plug it back in.
> > > This is my code right now:

> > > def GetGPS():
> > >       data = []
> > >       #Open com1: 9600,8,N,1
> > >       fi = serial.Serial(0, timeout = 1)
> > >       print '[gps module] SERIAL PORT OPEN ON COM1:'

> >http://docs.python.org/lib/node545.html

> I tried the code onto my codes but what came out was that in the line
> signal.signal(signal.SIGSLRM, handler), an attributeError appeared
> reading that 'module' object has no attribute 'SIGALRM'
> --
Are you writing your program on windows, or some other platform which is
not unix?


Yeah I'm using Windows 2000.


signal doesn't work on Windows. The timeout parameter to Serial should  
suffice...


--
Gabriel Genellina

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


Searching and replacing text ?

2008-05-02 Thread Oltmans
Hi,

I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.

For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -> Hotmail]]

I've to replace it with
[http://www.hotmail.com Hotmail]

I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')

p.sub('[',txt)
q.sub('\b',txt)

Give that I don't have very strong RegEX background, this doesn't look
very elegant. Is there some other way I can accomplish the same thing?
Moreover, please note that I'm using 'p' and 'q' for two regex and
then calling 'sub()' on both p and q. Can't I just do that by
employing one RegEx and then calling sub() only once?

Please enlighten me. Thanks in advance.

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


Re: SSL through python. possible ?

2008-05-02 Thread Mike Driscoll
On May 2, 1:20 pm, Heikki Toivonen <[EMAIL PROTECTED]> wrote:
> Mike Driscoll wrote:
> > On Apr 29, 8:56 am, TkNeo <[EMAIL PROTECTED]> wrote:
> >> I need to do SSL file transfer using python? Is there a library i can
> >> use ?
>
> >http://sandbox.rulemaker.net/ngps/m2/
>
> M2Crypto has since moved tohttp://chandlerproject.org/Projects/MeTooCrypto
>
> --
>   Heikki Toivonen

Whoops...I just went with the first link Google gave me. The link I
gave doesn't mention that the project has moved. Looks like the one
you link to is the 9th link on my Google search using the terms:
"python m2crypto".

Sorry if I spread misinformation though.

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


Re: list.index crashes when the element is not found

2008-05-02 Thread Nick J Chackowsky

TkNeo wrote:

WHAT ?

This is crazy


Crazy like a fox?

a = [1, 2, 3]
try:
a.index(99)
except:
a.append(99)
finally:
print a.index(99)

MY question: which exception should I actually be catching there?
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: list.index crashes when the element is not found

2008-05-02 Thread Gabriel Genellina

En Fri, 02 May 2008 15:25:13 -0300, TkNeo <[EMAIL PROTECTED]> escribió:


WHAT ?

This is crazy


crashes? Or raises a ValueError exception, which is perfectly normal?

--
Gabriel Genellina

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


Re: list.index crashes when the element is not found

2008-05-02 Thread TkNeo
On May 2, 1:58 pm, Nick J Chackowsky <[EMAIL PROTECTED]>
wrote:
> TkNeo wrote:
> > WHAT ?
>
> > This is crazy
>
> Crazy like a fox?
>
> a = [1, 2, 3]
> try:
>  a.index(99)
> except:
>  a.append(99)
> finally:
>  print a.index(99)
>
> MY question: which exception should I actually be catching there?
> ** Posted fromhttp://www.teranews.com**

ofcouse try catch is going to work but in ideality the index function
should return a -1 and no way in hell crash.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finally had to plonk google gorups.

2008-05-02 Thread Mensanator
On May 2, 1:20 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> Mensanator wrote:
> > On May 2, 9:53 am, Michael Torrie <[EMAIL PROTECTED]> wrote:
> >> Shawn Milochik wrote:
> >>> How does one "plonk" stuff from Google Groups? Specifically, how
> >>> can this be done in Gmail?
> >> Set up a filter that looks for some phrase in the mail headers that
> >> identifies messages originating from google groups.  Gmail's filters are
> >> fairly flexible.  I'd probably just have it look for certain words.
> >> Look at an e-mail's source (raw view) and particularly check in the
> >> headers for things to filter by.
>
> > Why don't you just block all messages from Gmail?
>
> Brilliant!  Seeing as he's asking about doing the filtering in Gmail
> (implying it's use for his own posting and viewing the list) that would
> work splendidly for him!  Or not.
>
> Of course you're not likely to see this message either since I and many
> folks on here post from gmail.
>
> Spam comes mainly from Google Groups, not as much from Gmail in my
> experience.

I didn't say it was POSTED from gmail, but the spammers often have
gmail addresses, to wit:

 age of empires 3 crack serial  1 [EMAIL PROTECTED] (1
author) Apr 30
 microsoft office word 2007 keygen download 1
[EMAIL PROTECTED] (1 author) Apr 30
 ulead video studio 8 serial crack  1 [EMAIL PROTECTED] (1
author) Apr 30
 daylight savings time patch1 [EMAIL PROTECTED] (1 author)
Apr 30
 the sims 2 crack   1 [EMAIL PROTECTED] (1 author) 
Apr 30
 fifa manager 08 crack  1 [EMAIL PROTECTED] (1 author)
Apr 30
 autocad 2005 cracks and cheats 1 [EMAIL PROTECTED] (1
author) Apr 30
 rar password crack 2 [EMAIL PROTECTED] (1 author) 
Apr
30
 crack rock cooking 1 [EMAIL PROTECTED] (1 author) 
Apr
30
 vws crack  2 [EMAIL PROTECTED] (1 author) 
Apr 30

Why aren't you blaming gmail for it's contribution to the problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: pil:effbot and pythonware offline

2008-05-02 Thread Mike Driscoll
On May 1, 5:15 pm, spdegabrielle <[EMAIL PROTECTED]> wrote:
> Sorry, I'm new to python and was trying to get imageTK;
> this led me to try find PIL, but pythonware and effbot both seem to be
> offline.
>
> I can't find any mention of an outage on python.org, this newsgroup,
> or the planet-blogs.
>
> Is it just me? and does anyone know where I can find ImageTK?
>
> Cheers,
>
> stephen

They both seem to be up now. Maybe there was some simultaneous server
maintenance?

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


  1   2   >