发布时间:2022-08-09 文章分类:编程知识 投稿人:李佳 字号: 默认 | | 超大 打印

How to capture stdout in real-time with Python

This solution is thanks to this article.

import subprocess
def myrun(cmd):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)