从子流程获取进度消息 [英] Getting progress message from a subprocess

查看:22
本文介绍了从子流程获取进度消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启动一个需要几分钟才能完成的程序.在此期间,我想阅读程序的进度消息(打印在标准输出上).问题是我找不到在运行期间读出其输出的方法.

I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The problem is that I cannot find a way to read out its output during its run.

我发现读取程序输出的唯一函数是 Popen.communicate(),但此方法会等待进程完成.所以不可能以特殊的格式获取进度并让用户看到.

The only function I found to read out the output of a program is Popen.communicate(), but this method waits until the process finishes. So it is impossible to get the progress and make it visible to the user in a special formatted way.

是否有可能以另一种方式做到这一点?

Is it possible to do this another way?

当我使用 subprocess.popen 和我的脚本运行该进程时,我会在屏幕上看到程序的输出.有没有可能隐藏它?(Ubuntu 10.10,普通终端)

When I run the process with subprocess.popen with my script I see the output of the program on the screen. Is it possible to hide it? (Ubuntu 10.10, normal terminal)

推荐答案

最简单的是使用关键字参数 stdout=subprocess.PIPE 调用 Popen.

Simplest is to call Popen with the keyword argument stdout=subprocess.PIPE.

p = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
while True:
    line = p.stdout.readline()
    if not line:
        break
    print line

<小时>

要查看此操作,这里有两个示例脚本.将它们放在同一目录中并运行 python superprint.py

printandwait.py:

printandwait.py:

import time
import sys
print 10
sys.stdout.flush()
time.sleep(10)
print 20
sys.stdout.flush()

superprint.py:

superprint.py:

import subprocess
import sys
p = subprocess.Popen(["python printandwait.py"], shell=True, stdout=subprocess.PIPE)
while True:
    print "Looping"
    line = p.stdout.readline()
    if not line:
        break
    print line.strip()
    sys.stdout.flush()

这篇关于从子流程获取进度消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆