Flushing stdout
Steve Holden
steve at holdenweb.com
Mon Nov 1 16:41:04 EST 2004
Graham Ashton wrote:
> Hi. I'm having trouble flushing sys.stdout. I've written a small example
> to illustrate my problem (see below). In short, I expect it to ping
> "received hello", sleep for 5 seconds and then print "received world".
> Instead I get nothing for 5 seconds and then both statements pop out at
> once.
>
You aren't actually having trouble flushing sys.stdout at all ...
> As you'll no doubt gather from the example, the problem I'm really trying
> to solve is sending message back from one process to another via a pipe.
> Changing the buffering option in the os.pipe() call doesn't have any
> effect either.
>
Nope. The holdup is elsewhere.
> Any thoughts? Thanks.
>
> P.S. I've not found -u and PYTHONUNBUFFERED to help me.
>
Nope, they won't ...
> P.P.S. I'm running 2.3.3 on Linux, libc 2.2.5-11.5.
>
> ---cut---
> #!/usr/bin/env python
>
> import os, sys, time
>
> if len(sys.argv) > 1:
> sys.stdout.write("hello\n")
> sys.stdout.flush()
> time.sleep(5)
> sys.stdout.write("world\n")
> else:
> command = "python %s foo" % os.path.basename(sys.argv[0])
> for line in os.popen(command, "r", 1):
> print "received", line,
>
The iteration over the pipe's contents is waiting until it sees the end
of the output before it yields anything. Try this:
import os, sys, time
if len(sys.argv) > 1:
sys.stdout.write("hello\n")
sys.stdout.flush()
time.sleep(5)
sys.stdout.write("world\n")
else:
command = "python %s foo" % os.path.basename(sys.argv[0])
f = os.popen(command, "r", 1)
while 1:
line = f.readline()
if not line:
break
print "received", line,
You can probably find a tidier way to bundle this now you know what's up.
regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
More information about the Python-list
mailing list