如何捕获输出并使用Python同时显示它?
问题描述:
我有一个相当长的运行作业,运行几分钟然后重新启动。任务输出我捕获像这样的各种信息:如何捕获输出并使用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
答
你可以尝试这样的事情:
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
答
你可以一行一次读它:
from subprocess import Popen, PIPE
p = Popen('grep -ir graph .', stdout=PIPE)
while not p.returncode:
s = p.stdout.readline()
print s
p.poll()
这样,您只能处理输出单行所需的时间。
由于您没有指定缓冲区大小,因此两个进程之间会添加4KB缓冲区,所以它们通常不会相互阻塞。 –