0

Possible Duplicate:
read subprocess stdout line by line

I wrote a C++ program that generates all bunch of text in the Linux console.

I am using a python script to parse the output of this C++. I am doing this like that:

cmd = ["./starter"] 

p = subprocess.Popen(cmd, 
    stdout=subprocess.PIPE)

for line in p.stdout:

    strLine = str(line).rstrip()
    print(">>> " + strLine )

This is working. BUT i have a major problem, the output is not live. I mean by that, that after starting the script nothing is printed out, but only after couple second things are coming out.. It is almost like python is waiting a number of character max to then print them all at once...

Is there a way to tell python to print a line AS SOON AS it was printed by the C++ program ?

Community
  • 1
  • 1
Johny19
  • 5,364
  • 14
  • 61
  • 99

1 Answers1

1

You are using the stdout file as an iterator, and that uses a largish buffer, delaying your prints. Use .readline() instead; you can still make that into a loop using iter() with a sentinel:

for line in iter(p.stdout.readline, ''):
    strLine = str(line).rstrip()
    print(">>> " + strLine )

You can also add flush=True to your print function call:

print(">>> " + strLine, flush=True)

or, if you are on Python 2 instead of Python 3 (where print is a statement, not a function), you can directly flush the stdout buffer:

import sys

sys.stdout.flush()

By default, stdout is line-buffered, so python normally should flush the buffer whenever you print a newline.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343