Unbuffered subprocess output (last line missing)
Posted
by plok
on Stack Overflow
See other posts from Stack Overflow
or by plok
Published on 2010-03-12T12:10:14Z
Indexed on
2010/03/12
12:37 UTC
Read the original article
Hit count: 411
I must be overlooking something terribly obvious. I need to execute a C program, display its output in real time and finally parse its last line, which should be straightforward as the last line printed is always the same.
process = subprocess.Popen(args, shell = True,
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# None indicates that the process hasn't terminated yet.
while process.poll() is None:
# Always save the last non-emtpy line that was output by the child
# process, as it will write an empty line when closing its stdout.
out = process.stdout.readline()
if out:
last_non_empty_line = out
if verbose:
sys.stdout.write(out)
sys.stdout.flush()
# Parse 'out' here...
Once in a while, however, the last line is not printed. The default value for Popens's bufsize is 0, so it is supposed to be unbuffered. I have also tried, to no avail, adding fflush(stdout) to the C code just before exiting, but it seems that there is absolutely no need to flush a stream before exiting a program.
Ideas anyone?
© Stack Overflow or respective owner