这里已经有一个问题回答了如何处理关于 sys.stdout
和 sys.stderr
的内容: https://dev59.com/bGzXa4cB1Zd3GeqPY-Y8#14197079
但是这并不适用于所有情况。日志模块似乎会输出到 sys.stdout
和 sys.stderr
,但我无法使用上述的上下文管理器来捕获它。
在下面的示例代码中,我试图捕获上下文管理器内的所有输出,但无法捕获日志记录语句:
from __future__ import print_function
import contextlib
import sys
import logging
from StringIO import StringIO
# taken from https://dev59.com/bGzXa4cB1Zd3GeqPY-Y8#14197079
@contextlib.contextmanager
def stdout_redirect(where):
prev_stdout = sys.stdout
prev_stderr = sys.stderr
prev_stdout.flush()
sys.stdout = where
sys.stderr = where
try:
yield where
finally:
where.flush()
sys.stdout = prev_stdout
sys.stderr = prev_stderr
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
print("\t\tOUTSIDE: stdout", file=sys.stdout)
print("\t\tOUTSIDE: stderr", file=sys.stderr)
logger.info("\tOUTSIDE: info")
logger.debug("\tOUTSIDE: debug")
logger.warn("\tOUTSIDE: warn")
logger.error("\tOUTSIDE: error")
logger.critical("\tOUTSIDE: critical")
print("=============== DIVIDER ================")
s = ""
with stdout_redirect(StringIO()) as new_stdout:
print("\t\tINSIDE: stdout", file=sys.stdout)
print("\t\tINSIDE: stderr", file=sys.stderr)
logger.info("\tINSIDE: info")
logger.debug("\tINSIDE: debug")
logger.warn("\tINSIDE: warn")
logger.error("\tINSIDE: error")
logger.critical("\tINSIDE: critical")
print("=============== DIVIDER ===============")
print(new_stdout.getvalue())
print("=============== LOGGING ===============")
print(logger.handlers)
print(logger.root.handlers)
我该如何暂时重定向记录器输出到stdout并捕获它们?我查看了logging/init.py,但它没有立即告诉我需要做什么。
我的动机是想为一个庞大的代码库配备测试,每个测试都捕获所调用的大量日志输出。我可以捕获外部程序,但似乎无法捕获我在nose中运行的测试。
目前不能重新编写冗长的部分,但这绝对是未来的目标。
编辑,关于ubuntu
这是我尝试使用nosetests运行的内容:
from __future__ import print_function
import sys
def test_funky_shurane():
import logging
logging.basicConfig(level=logging.DEBUG)
logging.info("===== shurane info")
logging.warn("===== shurane warn")
logging.error("===== shurane error")
logging.critical("===== shurane critical")
print("===== shurane stdout", file=sys.stdout)
print("===== shurane stderr", file=sys.stderr)
assert True
然后使用以下命令运行:
nosetests test_logging.py
nosetests --nocapture test_logging.py
nose
带有--nocapture
标志运行? - unutbulogging
非常灵活,可以输出到多个源;我只是在寻找那些输出到stdout/stderr的内容。 - Ehtesh Choudhury