【问题标题】:Capture continous output of external program捕获外部程序的连续输出
【发布时间】:2019-05-08 09:43:17
【问题描述】:

我正在尝试捕获 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,

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

【问题讨论】:

  • 这个问题有帮助吗? stackoverflow.com/questions/4760215/…我特别想vartec的回答好像很适合你
  • 尝试了 vartec 的解决方案(通过打印更改产量),但在欧芹完成后仍会一次打印所有“百分比”行。

标签: python python-2.7 subprocess


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 2012-07-30
    • 2013-01-10
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多