print without newline "halts" program execution

Jay Parlar jparlar at cogeco.ca
Fri Apr 14 00:02:51 EDT 2006


On Apr 13, 2006, at 5:57 PM, Karlo Lozovina wrote:

> Consider this short script:
>
> ---
> from time import time, sleep
>
> st = time()
> print 'Start: %f, ' % st,
> sleep(10)
> sp = time()
> print 'Stop: %f, Duration: %f' % (sp, (st - sp))
> ---
>
> On my environment (Linux, py24), when run, Python first waits 10s, and
> then produces the entire output. How, can I make it print first part
> ('Start: %f, '), then wait 10s, and then append (WITHOUT NEWLINE) that
> second print statement?
>
> I'm writting a script with lot of output which has to go on the same 
> line,
> but I don't want to wait for it to end to see output, I just want it to
> print parts as it's finished with them.
>
> Using sys.stdout.write() produces the same behavior, so what can I do?
> from time import time, sleep
>
>

Your problem is that the 'print' statement is sending the text to 
sys.stdout, and sys.stdout is buffered.

There are other ways to do this, but try this:

from time import time, sleep
import sys

st = time()
print 'Start: %f,'% st,
sys.stdout.flush()
sleep(10)
sp = time()
print 'Stop: %f, Duration: %f' % (sp, (st-sp))


Jay P.




More information about the Python-list mailing list