timer

Paul Moore p.f.moore at gmail.com
Mon Jun 29 18:38:01 EDT 2009


2009/6/29 MRAB <python at mrabarnett.plus.com>:
> superpollo wrote:
>>
>> hi folks.
>>
>> the follwing shoud print 'stuff' for 3 seconds and then stop. why it does
>> not work? (prints stuff forever)
>>
>>      1 #!/usr/bin/python
>>      2
>>      3 import threading
>>      4 import sys
>>      5
>>      6 t = threading.Timer(3.0, sys.exit)
>>      7 t.start()
>>      8 while True:
>>      9     print "stuff ",
>>
> The Timer runs the function in another thread. Perhaps sys.exit is just
> exiting that thread and not the main thread.

sys.exit raises a SystemExit exception, which will get handled in the
new thread (where it won't do anything). Conceded, this isn't
particularly intuitive.

For a non-toy example, you'd probably create an Event object, use your
timer to set the event, and your while loop would do while
event.is_set(), so the problem wouldn't arise.

Paul.



More information about the Python-list mailing list