无法从日志记录获取子进程标准输出

时间:2020-08-08 14:35:10

标签: python logging subprocess stdout

假设我有两个Python脚本:

第一个名为test.py的脚本使用logging输出一个“测试”

import logging

logging.info("Test")

第二个脚本使用subprocess调用第一个脚本并重定向IO。

import subprocess

p = subprocess.Popen(
        ['python',  'test.py'], 
        stdout=subprocess.PIPE, 
        stderr=subprocess.STDOUT)
print(p.stdout.read())

第二个脚本不输出任何内容,而是输出“测试”。 如果我将print("Test")替换为logging.info("Test"),一切正常。

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这里有两件事要注意:

  1. 默认情况下,日志记录级别设置为“警告”
  2. 日志被写入stderr,而不是stdout

一个简单的测试可以证明这一点,

$ python3 -c 'import logging; logging.info("hello world")'
$
$ python3 -c 'import logging; logging.warning("hello world")' >/dev/null
WARNING:root:hello world

>>> import sys
>>> 
>>> code = """import logging
... logging.warning("hello world")
... """
>>> 
>>> import subprocess
>>> subprocess.run([sys.executable, '-c', code], stdout=subprocess.PIPE)
WARNING:root:hello world
CompletedProcess(args=['/usr/bin/python3', '-c', 'import logging\nlogging.warning("hello world")\n'], returncode=0, stdout=b'') # see stdout is empty ?
>>> subprocess.run([sys.executable, '-c', code], stderr=subprocess.PIPE)
CompletedProcess(args=['/usr/bin/python3', '-c', 'import logging\nlogging.warning("hello world")\n'], returncode=0, stderr=b'WARNING:root:hello world\n') # see stderr have the data

注意: 您可能应该正确设置日志记录conf:)