除非设置了详细或调试标志,否则隐藏回溯错误的惯用 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
最佳答案
简单的方法是使用 sys
模块并使用以下命令:
sys.tracebacklimit = 0
使用您的标志来确定行为。
例子:
>>> import sys
>>> sys.tracebacklimit=0
>>> int('a')
ValueError: invalid literal for int() with base 10: 'a'
更好的方法是使用和exception hook :
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
编辑:
如果你仍然需要回退到原来的钩子(Hook)的选项:
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)
现在您可以将调试 Hook 传递给处理程序,但您很可能希望始终使用源自 sys.excepthook
的调试 Hook (因此在 debug_hook
中不传递任何内容>)。 Python 在定义时绑定(bind)默认参数一次(常见的陷阱...),这使得它在替换之前始终与相同的原始处理程序一起工作。
关于python - 除非设置了调试标志,否则隐藏回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674602/