Python sleep doesn't work right in a loop?
Diez B. Roggisch
deetsNOSPAM at web.de
Wed Apr 6 15:22:31 EDT 2005
ritterhaus at yahoo.com wrote:
> Just a simple bit of code to toggle between two state at intervals...
>
> import time
> for i in range(4):
> print 'On'
> time.sleep(1)
> print 'Off'
> time.sleep(1)
>
> ... SHOULD toggle On and Off four times with one-second pauses. When I
> run this, the loop pauses the full eight seconds then prints the Ons
> and Offs all at once. What's up with that?
Works for me - on a terminal using linux. BUT what not works is this:
python /tmp/test.py | cat
(test.py contains your code of course) The reason is buffered pipes being
used. Try this:
import time, sys
for i in range(4):
print 'On'
sys.stdout.flush()
time.sleep(1)
print 'Off'
sys.stdout.flush()
time.sleep(1)
--
Regards,
Diez B. Roggisch
More information about the Python-list
mailing list