假设我有两个Python脚本:
名为CCD_ 1的第一个脚本;测试";带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())
第二个脚本不输出任何内容;测试";。如果我用logging.info("Test")
替换print("Test")
,那么一切都很好。
如何解决这个问题?
这里需要注意两件事:
- 默认情况下,日志记录级别设置为警告
- 日志被写入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 loggingnlogging.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 loggingnlogging.warning("hello world")n'], returncode=0, stderr=b'WARNING:root:hello worldn') # see stderr have the data
注意:您可能应该正确设置日志配置文件:(