从 subprocess.communicate() 读取流输入 [英] Read streaming input from subprocess.communicate()

查看:61
本文介绍了从 subprocess.communicate() 读取流输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 的 subprocess.communicate() 从运行大约一分钟的进程中读取标准输出.

I'm using Python's subprocess.communicate() to read stdout from a process that runs for about a minute.

如何以流式方式打印出该进程 stdout 的每一行,以便我可以看到生成的输出,但在继续之前仍会阻止进程终止?

How can I print out each line of that process's stdout in a streaming fashion, so that I can see the output as it's generated, but still block on the process terminating before continuing?

subprocess.communicate() 似乎一次给出所有输出.

subprocess.communicate() appears to give all the output at once.

推荐答案

请注意,我认为 J.F.塞巴斯蒂安的方法(下)更好.

Please note, I think J.F. Sebastian's method (below) is better.

这是一个简单的例子(不检查错误):

Here is an simple example (with no checking for errors):

import subprocess
proc = subprocess.Popen('ls',
                       shell=True,
                       stdout=subprocess.PIPE,
                       )
while proc.poll() is None:
    output = proc.stdout.readline()
    print output,

如果 ls 结束得太快,那么 while 循环可能会在您读取所有数据之前结束.

If ls ends too fast, then the while loop may end before you've read all the data.

您可以通过这种方式在标准输出中捕获余数:

You can catch the remainder in stdout this way:

output = proc.communicate()[0]
print output,

这篇关于从 subprocess.communicate() 读取流输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆