gpt4 book ai didi

python - 无缓冲的子进程输出(最后一行缺失)

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:03 25 4
gpt4 key购买 nike

我一定是忽略了一些非常明显的东西。我需要执行一个 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 代码,但没有成功,但似乎完全没有必要在退出程序之前刷新流。

有人有想法吗?

最佳答案

问题是您一直在读取行,直到进程退出,(process.poll()),而由于 shell 标志,您确实使用了缓冲。

您必须继续阅读 process.stdout,直到到达文件末尾或空行。

关于python - 无缓冲的子进程输出(最后一行缺失),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2432556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com