我一定忽略了一些非常明显的东西。我需要执行一个 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 代码中,但无济于事,但似乎完全没有必要在退出程序之前刷新流。
任何人的想法?