time functions execute out of order

Posted by birrellwalsh on 2010-10-01 14:15

I ran this code both interactively and as a .py file:

import time
def a():
    print "starting"
    time.sleep(5)
    print "finishing"

a()

My intention was to have "starting" print at the beginning, then a five second pause, then to have "finishing" printed.

Instead when I run the program, nothing happens for (a bit more than) 5 seconds, then "starting" and "finishing" print right after each other with no pause between them.

The same thing happened when I replaced the time.sleep(5) function with a handmade 5-second-pause function.

Could anyone tell me what is happening?

Thanks.

sridharr
ActiveState Staff
Fri, 2010-10-01 15:13

You need flush the standard output stream. Try inserting sys.stdout.flush() after each print statement.

birrellwalsh | Fri, 2010-10-01 17:27

I thought that the sys.stdout.flush() would solve it. So I rewrote the code as

#------------- Code Begins ------------------

import time
import sys
def a():
print "starting"
sys.stdout.flush()
time.sleep(5)
print "finishing"
sys.stdout.flush()

a()

# the definition of a() was properly indented - that does
# not seem show in the posting...

#------------- Code Ends ------------------

The program still paused without writing anything - for more or less five seconds - and then wrote both "starting" and "finishing" at once.

This has happened on two machines, one using a 32 bit and one a 64 bit activestate community edition.

Thanks!

sridharr
ActiveState Staff
Fri, 2010-10-01 17:36

Hmm, the program does what it is supposed to do for me here, even without the calls to `flush` . I am guessing that there is something strange about those two machines. Out of curiosity, is this happening only with ActivePython (i.e., not the one from python.org)?

birrellwalsh | Fri, 2010-10-01 22:03

... and that was a project.

And the python.org version runs correctly. It shows "starting", pauses for 5 seconds, and then prints "finishing."

I wonder when the Activestate version will run as it should?