除非设置了调试标志,否则隐藏回溯

2024-01-10

除非设置了详细或调试标志,否则隐藏回溯错误的惯用Python方法是什么?

示例代码:

their_md5 = 'c38f03d2b7160f891fc36ec776ca4685'
my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7' 
if their_md5 != my_md5:
    raise ValueError('md5 sum does not match!')

现在已有输出,但只有在调用时才需要foo.py --debug:

Traceback (most recent call last):
  File "b:\code\apt\apt.py", line 1647, in <module>
    __main__.__dict__[command] (packages)
  File "b:\code\apt\apt.py", line 399, in md5
    raise ValueError('md5 sum does not match!')
ValueError: md5 sum does not match!

期望的正常输出:

ValueError: md5 sum does not match!

这是一个测试脚本:https://gist.github.com/maphew/e3a75c147cca98019cd8 https://gist.github.com/maphew/e3a75c147cca98019cd8


最短的方法是使用sys模块并使用此命令:

sys.tracebacklimit = 0

使用您的标志来确定行为。

Example:

>>> import sys
>>> sys.tracebacklimit=0
>>> int('a')
ValueError: invalid literal for int() with base 10: 'a'

更好的方法是使用和异常钩子 https://docs.python.org/2/library/sys.html#sys.excepthook:

def exception_handler(exception_type, exception, traceback):
    # All your trace are belong to us!
    # your format
    print "%s: %s" % (exception_type.__name__, exception)

sys.excepthook = exception_handler

Edit:

如果您仍然需要回退到原始挂钩的选项:

def exception_handler(exception_type, exception, traceback, debug_hook=sys.excepthook):
    if _your_debug_flag_here:
        debug_hook(exception_type, exception, traceback)
    else:
        print "%s: %s" % (exception_type.__name__, exception)

现在您可以将调试挂钩传递给处理程序,但您很可能希望始终使用源自sys.excepthook(所以什么都不传入debug_hook)。 Python 绑定默认参数once在定义时间(常见陷阱...),这使得它在替换之前始终与相同的原始处理程序一起工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

除非设置了调试标志,否则隐藏回溯 的相关文章

随机推荐