使用doctest并登录python程序 [英] use doctest and logging in python program

查看:73
本文介绍了使用doctest并登录python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


#!/usr/bin/python2.4
import logging
import sys
import doctest
def foo(x):
        """
    >>> foo (0)
    0
        """
        print ("%d" %(x))
        _logger.debug("%d" %(x))
def _test():
        doctest.testmod()
_logger = logging.getLogger()
_logger.setLevel(logging.DEBUG)
_formatter = logging.Formatter('%(message)s')
_handler = logging.StreamHandler(sys.stdout)
_handler.setFormatter(_formatter)
_logger.addHandler(_handler)
_test()

我想对所有我的打印语句使用记录器模块.我查看了前50个Google顶级链接,他们似乎同意doctest使用它自己的stdout副本. 如果使用打印,则在使用记录器的情况下,它将记录到根控制台. 有人可以用代码片段演示一个工作示例,让我结合起来. 请注意,运行鼻子测试doctest只会在测试结束时追加日志输出,(假设您设置了开关),不会将它们视为打印语句.

I would like to use logger module for all of my print statements. I have looked at the first 50 top google links for this, and they seem to agree that doctest uses it's own copy of the stdout. If print is used it works if logger is used it logs to the root console. Can someone please demonstrate a working example with a code snippet that will allow me to combine. Note running nose to test doctest will just append the log output at the end of the test, (assuming you set the switches) it does not treat them as a print statement.

推荐答案

我不确定为什么要这样做,但是如果确实需要这样做,则可以定义自己的DocTestRunner子类,并覆盖run方法:

I'm not sure why you want to do this, but if you really need to do it, then you can define your own subclass of DocTestRunner, and override the run method:

#imports left out, code not tested - just to point you in the right direction
class MyDocTestRunner(DocTestRunner):
    def run(self, test, compileflags=None, out=None, clear_globs=True):
        if out is None:
            handler = None
        else:
            handler = StreamHandler(out)
        logger = logging.getLogger() # root logger (say)
        if handler:
            logger.addHandler(handler)
        try:
            DocTestRunner.run(self, test, compileflags, out, clear_globs)
        finally:
            if handler:
                logger.removeHandler(handler)
                handler.close()

然后使用此跑步者代替DocTestRunner.

Then use this runner in place of DocTestRunner.

这篇关于使用doctest并登录python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆