【问题标题】:Python subprocess output to stdoutPython 子进程输出到标准输出
【发布时间】:2011-08-29 01:45:42
【问题描述】:

我正在使用 subprocess 模块从 python 运行二进制文件。

为了捕获二进制文件产生的输出,我使用:

proc = subprocess.Popen (command_args, shell=False, stdout=subprocess.PIPE)
out = proc.communicate()[0]
#print the output of the child process to stdout
print (out)

它的作用是在进程完成执行后打印进程的输出。无论如何我可以在程序执行时将此输出打印到标准输出吗?我真的需要看看输出是什么,因为这些程序可以运行很长时间。

感谢您的帮助。

【问题讨论】:

  • 没关系,伙计们,我想我找到了解决方案:Basically you have 3 options: Use threading to read in another thread without blocking the main thread. select on stdout, stderr instead of communicate. This way you can read just when data is available and avoid blocking. Let a library solve this, twisted is a obvious choice.
  • 如果您找到其他答案,例如 *.com/questions/4585692/… ,请链接到它,而不是在您自己的问题的评论中复制答案。
  • 很抱歉。我认为评论中的重点是*.com/questions/4585692/的精髓……下次我会记住这一点

标签: python subprocess stdout


【解决方案1】:

只是不要将输出发送到管道:

proc = subprocess.Popen (command_args, shell=False)
proc.communicate()

【讨论】:

  • @josh:是的,这是意料之中的,也是代码不将结果存储在变量中的原因。由于我们不将输出发送到管道,因此子进程将从当前进程继承 stdout,这意味着所有内容都将直接打印到终端。
  • 对不起,你是对的——我没有仔细阅读这个问题,我以为他想做我想做的事,那就是让两者……实时输出到stdout,然后捕获输出
  • @josh:如果您可以在等待输出时阻塞,并且处理输出不会花费很长时间,您可以简单地将参数 bufsize=1 传递给 Popen() 用于行缓冲,逐行读取输出,一拿到就打印出来并处理。
  • 不错的技巧,我可以看到 cmd 上打印的行,如何将其存储到我以后可以使用的变量中?