捕获外部程序的连续输出

时间:2019-05-08 09:43:17

标签: python python-2.7 subprocess

我正在尝试捕获AtomicParsley的输出,该输出在欧芹运行时像

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,

我已经阅读了所有类似的答案,但它们似乎都不符合我的需要(我需要打印的行才能显示进度条)。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您的程序似乎挂起,因为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
相关问题