捕获外部程序的连续输出

2024-09-30 01:30:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕捉原子欧芹的输出,它像欧芹一样流动

Started writing to temp file.
 Progress: >0%-----------------------------------------------------------------------------|
 Progress: =>1%----------------------------------------------------------------------------|
 Progress: ==>2%---------------------------------------------------------------------------|
    ...
 Progress: ======================================================================>95%--|
 Progress: =======================================================================>96%--|
 Progress: ========================================================================>97%--|
 Progress: =========================================================================>98%--|
 Progress: ==========================================================================>99%--|
 Progress: ===========================================================================>100%|
Finished writing to temp file.

但当它完成的时候,所有的东西都会立刻印出来。 我的代码是:

process = subprocess.Popen([atomicparams], shell=True, stdout=PIPE)
for line in iter(process.stdout.readline, ""):
    print line,

我读过所有类似的答案,但它们似乎不符合我的需要(我需要打印的行来输入进度条)。 有人能帮忙吗?你知道吗


Tags: to代码stdoutlineprocesstempfilesubprocess
1条回答
网友
1楼 · 发布于 2024-09-30 01:30:30

您的程序似乎挂起了,因为AtomicParsley从不返回一行,而是使用转义码一次又一次地删除同一行,然后重新打印以获得动态输出。为了在终端中重现这一点,您可以在父进程可用时逐字符打印它。你知道吗

import subprocess
import sys

p = subprocess.Popen([atomicparams], stdout=subprocess.PIPE)
while(True):
    # returns None while subprocess is running
    retcode = p.poll() 
    sys.stdout.buffer.write(p.stdout.read(1))
    sys.stdout.buffer.flush()
    if retcode is not None:
        break

相关问题 更多 >

    热门问题