How can I capture the stdout output of a child process?

@Paolo’s solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way:

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

while True:
    out = process.stdout.readline(1)
    if out == '' and process.poll() != None:
        break
    if out.startswith('myline'):
        sys.stdout.write(out)
        sys.stdout.flush()

Leave a Comment