Capture subprocess output [duplicate]

communicate() blocks until the child process returns, so the rest of the lines in your loop will only get executed after the child process has finished running. Reading from stderr will block too, unless you read character by character like so:

import subprocess
import sys
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
while True:
    out = child.stderr.read(1)
    if out == '' and child.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

This will provide you with real-time output. Taken from Nadia’s answer here.

Leave a Comment