【问题标题】:How can I capture output and show it at the same time with Python?如何使用 Python 捕获输出并同时显示它?
【发布时间】:2011-12-20 03:22:16
【问题描述】:

我有一个运行时间很长的作业,它运行了几分钟,然后重新启动。该任务输出我捕获的各种信息,如下所示:

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

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以试试这样的:

    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
    

    【讨论】:

      【解决方案2】:

      你可以一次读一行:

      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的缓冲区,所以通常不会互相阻塞。
      【解决方案3】:

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

      【讨论】:

      • 是的,但我需要在 Python 中处理缓冲区,以了解是否应该再次启动任务。
      • OP 询问是否监控他们使用 popen 从 Python 代码内部启动的进程,因此这没有帮助。
      猜你喜欢
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2010-11-19
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多