如何在Python中捕获并同时显示输出?

8 投票
3 回答
2262 浏览
提问于 2025-04-17 05:29

我有一个运行时间比较长的任务,它会运行几分钟,然后重新启动。这个任务会输出各种信息,我是这样捕获这些信息的:

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

3 个回答

-1

你可以使用“tee”这个命令。它正好能满足你的需求。
http://www.computerhope.com/unix/utee.htm

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()

这样的话,你只需要等处理输出一行的时间。

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

撰写回答