如何抑制我导入的模块的stdout日志输出?

时间:2016-01-29 15:52:59

标签: python python-2.7 logging stdout

我正在导入一个使用Python的foo模块的模块logging。但是,foo会产生大量的日志记录输出,我需要使用stdout向用户传达重要信息,这很大程度上被我导入的模块的荒谬输出所淹没

如何在不修改stdout代码的情况下禁用模块登录foo的功能?我仍然希望它记录到它记录的文件,但我不希望它记录到stdout

我尝试了以下内容:

logging.getLogger("foo").propagate = False

@contextlib.contextmanager
def nostdout():
    class DummyFile(object):
        def write(self, x): pass
    save_stdout = sys.stdout
    sys.stdout = DummyFile()
    yield
    sys.stdout = save_stdout

with nostdout(): import foo

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

logging.getLogger(<logger_name_used_in_foo>).propagate = False

答案 1 :(得分:1)

I'm referencing this article. 通常,如果要捕获写入stdout的任何内容,可以使用Python 3中的contextlib

from contextlib import redirect_stdout

f = io.StringIO()
with redirect_stdout(f):
    print('foobar')
    call_annoying_module()
print('Stdout: "{0}"'.format(f.getvalue()))

在Python 3.4及更早版本中,redirect_stdout可以像这样实现:

from contextlib import contextmanager

@contextmanager
def stdout_redirector(stream):
    old_stdout = sys.stdout
    sys.stdout = stream
    try:
        yield
    finally:
        sys.stdout = old_stdout

如果库中有任何使用puts打印的C绑定,那么它会变得更复杂。请参阅文章。

最简单的情况是当您使用subprocess运行其他程序时, 然后可以轻松捕获所有stdout输出。

proc = subprocess.Popen("echo output".split(), stdout=subprocess.PIPE)
std_output, err_output = proc.communicate()