假设我有两个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")
,一切正常。
如何解决这个问题?
答案 0 :(得分:2)
这里有两件事要注意:
一个简单的测试可以证明这一点,
$ 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:)