print without newline "halts" program execution

K

Karlo Lozovina

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?

Thanks a lot in advance.
 
J

Jay Parlar

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.
 
K

Karlo Lozovina

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

I thought it was something like this, but I couldn't find it in the docs :
(.
print 'Start: %f,'% st,
sys.stdout.flush()
sleep(10)
sp = time()
print 'Stop: %f, Duration: %f' % (sp, (st-sp))

This works excellent, *thank* you.
There are other ways to do this, but try this:

And for purely academical purposes, what are those other ways to do it?
I'm curious :).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top