使用 Python 中的子进程从进程中无缓冲读取 [英] Unbuffered read from process using subprocess in Python
本文介绍了使用 Python 中的子进程从进程中无缓冲读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从一个产生漫长而耗时的输出的进程中读取数据.但是,我想在 和何时 生成它的输出.但是使用类似下面的东西似乎正在缓冲命令的输出,所以我最终得到了所有的输出行:
I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output as and when it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
我正在 MacOS 10.5 上尝试此操作
I am trying this on MacOS 10.5
推荐答案
文件迭代器正在做一些内部缓冲 自己.试试这个:
The file iterator is doing some internal buffering on its own. Try this:
line = p.stdout.readline()
while line:
print line
line = p.stdout.readline()
您还需要确保您正在运行的进程实际上经常刷新其输出缓冲区.
You also need to make sure the process you are running is actually flushing its output buffers frequently.
这篇关于使用 Python 中的子进程从进程中无缓冲读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文