我需要逐行读取使用回车符 (\r) 进行输出的程序的输出。该程序运行了很长时间,因此我需要在程序运行时读取输出。我知道当每个输出项出现在新行上时如何执行此操作(详见 here ),但我似乎无法让它与回车一起使用。
这是我用来尝试让它工作的代码(在 linux 系统上运行)
import subprocess
command = ["printf", "".join(["Return count: " + str(x) + "\\r" for x in range(10)]) + "\n"]
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
buf = bytearray()
out = proc.stdout
while True:
c = out.read()
if c == b"":
break
if c == "\r":
print(buf)
buf = bytearray()
else:
buf += c
print("Done")
然而代码只是立即退出,打印Done。
我要打印代码:
Return code: 1
Return code: 2
Return code: 3
等我需要修改什么才能使其正常工作?
请您参考如下方法:
