Python - 捕获Popen stdout并在控制台上显示?

时间:2009-08-15 22:48:42

标签: python pipe popen

我想从subprocess.Popen(...)启动的长时间运行流程中捕获stdout,因此我使用stdout=PIPE作为arg。

但是,因为它是一个长时间运行的进程,我还想将输出发送到控制台(好像我没有管道它),以便让脚本用户知道它仍在工作。

这一切都可能吗?

干杯。

5 个答案:

答案 0 :(得分:5)

缓存你的长时间运行的子进程可能正在执行将使你的控制台输出生涩和非常糟糕的用户体验。我建议您考虑使用pexpect(或者,在Windows上,wexpect)来阻止此类缓冲,并从子流程获得平滑,规则的输出。例如(在任何unix-y系统上,安装pexpect之后):

>>> import pexpect
>>> child = pexpect.spawn('/bin/bash -c "echo ba; sleep 1; echo bu"', logfile=sys.stdout); x=child.expect(pexpect.EOF); child.close()
ba
bu
>>> child.before
'ba\r\nbu\r\n'

ba和bu将以适当的时间(它们之间大约一秒钟)到来。请注意,输出不受正常的终端处理,因此回车留在那里 - 如果需要{{1,您需要自己对字符串进行后处理(只需一个简单的.replace! - )作为行尾标记(如果子进程将二进制数据写入其stdout,则缺少处理非常重要 - 这可确保所有数据保持完整! - 。)。

答案 1 :(得分:2)

S上。 Lott的评论指向Getting realtime output using subprocessReal-time intercepting of stdout from another process in Python

我很好奇Alex的答案与他的答案1085071不同。 我对其他两个引用问题中的答案进行了简单的小实验,结果很好......

我按照亚历克斯的回答看了看wexpect,但我不得不说读代码中的注释我对使用它没有很好的感觉。

我想这里的元问题是什么时候pexpect / wexpect会成为包含的电池之一?

答案 2 :(得分:1)

当您从管道中读取它时,可以简化print吗?

答案 3 :(得分:1)

或者,您可以将流程导入tee并仅捕获其中一个流。 类似sh -c 'process interesting stuff' | tee /dev/stderr

的内容

当然,这只适用于类Unix系统。

答案 4 :(得分:1)

受上面某处pty.openpty()建议的启发,在python2.6,linux上测试过。发布,因为它需要一段时间才能使其正常工作,没有缓冲......

def call_and_peek_output(cmd, shell=False):
    import pty, subprocess
    master, slave = pty.openpty()
    p = subprocess.Popen(cmd, shell=shell, stdin=None, stdout=slave, close_fds=True)
    os.close(slave)
    line = ""
    while True:
        try:
            ch = os.read(master, 1)
        except OSError:
            # We get this exception when the spawn process closes all references to the
            # pty descriptor which we passed him to use for stdout
            # (typically when it and its childs exit)
            break
        line += ch
        sys.stdout.write(ch)
        if ch == '\n':
            yield line
            line = ""
    if line:
        yield line

    ret = p.wait()
    if ret:
        raise subprocess.CalledProcessError(ret, cmd)

for l in call_and_peek_output("ls /", shell=True):
    pass
相关问题