How to capture stdout in real-time with Python

import subprocess

def myrun(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        print line,
        if line == '' and p.poll() != None:
    return ''.join(stdout)
def run_command(command):
    process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
        if output:
            print output.strip()
    rc = process.poll()
    return rc

The poll() method will return the exit code if the process is completed. None if the process is still running.

results matching ""

    No results matching ""