1

I have a Python GUI application that calls another Python script using the subprocess.Popen call. I have a Tkinter Text box in my GUI in which I would like to display the output of the subprocess. On OS X this works flawlessly, but on Windows 7 the output is not displayed in the Text box until the subprocess is finished running. How can I get the output to print in real time on Windows?

Code to start the subprocess:

p = Popen(command, stdout=PIPE, stderr=STDOUT, bufsize=1, close_fds=ON_POSIX)
t = Thread(target=read_and_print, args=(p, log_output))
t.daemon = True
t.start()

Function to print the output to the Text box. This is run in a separate thread so that the GUI does not hang while the subprocess executes.

def read_and_print(process, textarea):
    out = process.stdout

    for line in iter(out.readline, b''):
        textarea.insert(END, line)
        textarea.see(END)
        #this triggers an update of the text area, otherwise it doesn't update
        textarea.update_idletasks()
MattL
  • 1,132
  • 10
  • 23
  • possible duplicate of [Issues intercepting subprocess output in real time](http://stackoverflow.com/questions/27327886/issues-intercepting-subprocess-output-in-real-time) – Terry Jan Reedy Dec 12 '14 at 01:08
  • The solutions in the linked question produce the same result as the code in my question. – MattL Dec 12 '14 at 15:31

1 Answers1

1

The issue was that Python running on Windows was holding STDERR in a buffer until the command finished running(!?).

The solution is to tell Python to run without buffering its output with the -u flag. This makes the command I pass to subprocess.Popen

["python", "-u", "myprogram.py"]

instead of

["python", "myprogram.py"]
MattL
  • 1,132
  • 10
  • 23