Possible Duplicate:
Assignment Condition in Python While Loop
What’s the equivalent of this:
while (line = p.stdout.readline()) != '':
...
in Python?
I don’t like having to do this:
line = p.stdout.readline()
while line != '':
sys.stdout.write(line)
line = p.stdout.readline()
Although I’ve been using the latter for years… I suspect there is no alternative. I thought p.stdout supported iteration, like
for line in p.stdout:
sys.stdout.write(line)
but unfortunately it doesn’t, unlike the handle returned from open() for example.
Edit: Sorry, I was wrong, it does support it, the problem is that I can’t get it out right away like I can with p.stdout.readline(). Adding sys.stdout.flush() doesn’t seem to help, so it must be getting buffered inside p.stdout.
You can accomplish this using the built-in function
iter()using the two-argument call method:Documentation for this:
edit: Based on your edit it looks like your actual problem is related to buffering. Based on the context I am guessing you are using
subprocess.Popen()withstdout=subprocess.PIPE. Instead of using the file handlep.stdoutdirectly you should bep.communicate()to read the output of your subprocess.