2011-11-02 72 views
7

我有一个相当长的运行作业,运行几分钟然后重新启动。任务输出我捕获像这样的各种信息:如何捕获输出并使用Python同时显示它?

output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate() 

事情是,我一次只能得到整个输出。我想显示输出为程序发送到标准输出,同时仍然推回到缓冲区(我需要检查输出是否存在一些字符串)。在Ruby中我会做这样的:

IO.popen(cmd) do |io| 
    io.each_line do |line| 
    puts line 
    buffer << line 
    end 
end 

回答

5

你可以尝试这样的事情:

cmd = ["./my_program.sh"] 
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE) # launch the process 
while p.poll() is None:   # check if the process is still alive 
    out = p.stdout.readline() # if it is still alive, grab the output 
    do_something_with(out)  # do what you want with it 
3

你可以一行一次读它:

from subprocess import Popen, PIPE 

p = Popen('grep -ir graph .', stdout=PIPE) 
while not p.returncode: 
    s = p.stdout.readline() 
    print s 
    p.poll() 

这样,您只能处理输出单行所需的时间。

+0

由于您没有指定缓冲区大小,因此两个进程之间会添加4KB缓冲区,所以它们通常不会相互阻塞。 –

-1

您可以使用“tee”命令。它完全符合你的需求。
http://www.computerhope.com/unix/utee.htm

+0

是的,但我需要在Python中处理缓冲区,以了解是否应该再次启动任务。 – Geo

+0

OP在询问有关从Python代码中使用popen监控它们启动的进程的问题,因此这没有帮助。 – cowbert

相关问题