【问题标题】:How to run a non ending process via subprocess and collect both STDOUT and STDERR separately如何通过子进程运行非结束进程并分别收集 STDOUT 和 STDERR
【发布时间】:2019-04-09 19:40:08
【问题描述】:

我有一个执行subprocess.Popen的python程序,像这样;

process = subprocess.Popen(stand_alone_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print "out: ", out
print "err: ", err

如果我的stand_alone_command 将永远运行,我如何获取stand_alone_command 向 STDOUT 和 STDERR 抛出的任何内容,以便我可以记录它。

【问题讨论】:

标签: python subprocess


【解决方案1】:

尝试从 stdout 读取而不是调用 communicate() 等..

import subprocess
sac = ['tail', '-f', '/var/log/syslog']
process = subprocess.Popen(sac, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while 1:
    line = process.stdout.readline()
    if line:
        print(line)

我认为您需要设置shell=False,但我使用的是 Linux,Windows 有点不同。

【讨论】:

  • 这将“工作”,直到 stderr 的缓冲区已满并且整个事情陷入僵局。
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2021-03-20
  • 2011-07-07
  • 2020-06-23
相关资源
最近更新 更多