【问题标题】:Cannot get subprocess stdout from logging无法从日志记录中获取子进程标准输出
【发布时间】:2020-11-28 15:55:10
【问题描述】:

假设我有两个 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"),一切正常。

如何解决这个问题?

【问题讨论】:

    标签: python logging subprocess stdout


    【解决方案1】:

    这里有两点需要注意:

    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
    

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

    【讨论】:

    • 另一种解决方案:将logging.getLogger().setLevel(logging.INFO) 添加到 test.py 也可以。
    • 当然。我只是指出,给定的代码没有任何日志记录集。所以这就是为什么没有数据出来的原因:)。但是,是的,您应该根据需要正确设置日志记录配置
    猜你喜欢
    • 2011-11-11
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2017-11-06
    • 1970-01-01
    • 2012-07-18
    • 2020-10-12
    相关资源
    最近更新 更多