题
我必须俯瞰着的东西非常显而易见的。我需要执行一C节目,显示出在真正的时间和最后分析其最后一行,应该简单明了作为最后的线打印 总是 相同。
process = subprocess.Popen(args, shell = True,
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# None indicates that the process hasn't terminated yet.
while process.poll() is None:
# Always save the last non-emtpy line that was output by the child
# process, as it will write an empty line when closing its stdout.
out = process.stdout.readline()
if out:
last_non_empty_line = out
if verbose:
sys.stdout.write(out)
sys.stdout.flush()
# Parse 'out' here...
一旦在一段时间,但是,最后的线是不打印。默认值Popens的 bufsize 为0,所以它被认为是无缓冲。我也试过了,没有用的,加入 fflush(stdout) 对C码只是在退出之前,但似乎没有绝对需要冲洗一流之前的退出程序。
想法的人吗?
解决方案
readline()
已经缓冲区的文本,等待着一个新的线.
你总是有一个比赛条件的任何数量的联合国缓冲流将处理事实上,你正在处理一个线,然后检查退出,然后读取行,因此,如果子进程的退出而你正在处理一个线,你会不会读任何东西。此外壳是可能引入自己的缓冲。
所以你可以:
使用
communicate()
并给予了详细的输出时的子进程在运行。确保你继续读后进程已退出,直到获得EOF.
我也建议改变你的代码这样,你没有用 shell=True
.
其他提示
的问题是,你正在阅读线直到该过程退出,(process.poll()
),而你就使用,因为壳标志缓冲。
您将不得不直到你到达文件或空行的末尾保持读数process.stdout。
不隶属于 StackOverflow