我正在使用 Python 的 subprocess.communicate()
从运行大约一分钟的进程中读取标准输出。
如何以流方式打印出该进程的 stdout
的每一行,以便我可以看到生成的输出,但在继续之前仍会阻止进程终止?
subprocess.communicate()
似乎一次性给出所有输出。
最佳答案
在子进程刷新其标准输出缓冲区后,逐行获取子进程的输出:
#!/usr/bin/env python2
from subprocess import Popen, PIPE
p = Popen(["cmd", "arg1"], stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print line,
p.wait() # wait for the subprocess to exit
iter()
用于在写入行后立即读取行,以解决方法 the read-ahead bug in Python 2 .
如果子进程的标准输出在非交互模式下使用 block 缓冲而不是行缓冲(这会导致输出延迟,直到子进程的缓冲区已满或被子进程显式刷新),那么您可以尝试强制使用 pexpect
, pty
modules 的无缓冲输出或 unbuffer
, stdbuf
, script
utilities ,见 Q: Why not just use a pipe (popen())?
这是 Python 3 代码:
#!/usr/bin/env python3
from subprocess import Popen, PIPE
with Popen(["cmd", "arg1"], stdout=PIPE, bufsize=1,
universal_newlines=True) as p:
for line in p.stdout:
print(line, end='')
注意:不像 Python 2 那样输出子进程的字节串; Python 3 使用文本模式(cmd 的输出使用 locale.getpreferredencoding(False)
编码解码)。
关于python - 从 subprocess.communicate() 读取流输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2715847/