Unbuffered subprocess output (last line missing)

I have to lose sight of something terrible. I need to execute a C program, display its output in real time, and finally parse its last line, which should be simple, since 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...

From time to time, however, the last line is not printed. The default value for popens bufsize is 0, so it should be unbuffered. I also tried, to no avail, to add fflush (stdout) to the C code just before exiting, but it seems like there is absolutely no need to clear the stream before exiting the program.

Anyone ideas?

+3
source share
2

readline() , .

- , , , , , , , . , , , .

, :

  • communicate() .

  • , , EOF.

, shell=True.

+2

, (process.poll()), - .

process.stdout, .

+3

Source: https://habr.com/ru/post/1736649/


All Articles