繁体   English   中英

在 python 子进程中捕获 logger.info 输出?

[英]Catching logger.info output in python subprocess?

你好.py:

import logging
logging.info("hello, I am a log")

包装器.py:

import subprocess
from subprocess import PIPE

result = subprocess.run('python ./hello.py'.split(' '), stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(f'returncode: {result.returncode}')
print(f'stdout: {result.stdout}')
print(f'stderr: {result.stderr}')

当我调用python wrapper.py ,我希望看到这个输出:

returncode: 0
stdout: INFO:root:hello, I am a log
stderr: 

但是,我得到了这个输出:

returncode: 0
stdout:
stderr: 

而且,如果我用logger.warning()替换logging.info() logger.warning() ,那么我会得到这个输出:

returncode: 0
stdout:
stderr: WARNING:root:hello, I am a log

但是,我有一堆带有logging.info的代码,我想将它摄取到 python 子进程中。 我该怎么做?


最后说明:

  • 我想大多数人更愿意通过执行import hello来调用hello.py ,但假设在这种情况下这不是一个选项。
  • 我正在使用 Python 3.8。

好的,让这个有一个答案,然后,为潜在的未来读者。

logging.getLogger().setLevel(logging.INFO)hello.py 正如用户 blues 指出的那样,默认的日志记录级别是警告。 因此,当您使用不会产生任何输出的logging.info() ,这就是您看不到它的原因。

https://docs.python.org/3/library/logging.html#logging.Logger.setLevel查看更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM