Skip to main content
 首页 » 编程设计

python之从子进程读取回车分隔输出

2025年02月15日13think

我需要逐行读取使用回车符 (\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 

等我需要修改什么才能使其正常工作?

请您参考如下方法:

如果你想一个字节一个字节地获取,你需要传递一些字节才能到达read method :

c = out.read(1) 

否则,它将读取全部内容。