mat*_*kie 43 python error-handling user-experience
除非设置了详细或调试标志,否则隐藏回溯错误的惯用python方法是什么?
示例代码:
their_md5 = 'c38f03d2b7160f891fc36ec776ca4685'
my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7'
if their_md5 != my_md5:
raise ValueError('md5 sum does not match!')
Run Code Online (Sandbox Code Playgroud)
现在输出,但只有在调用时才需要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!
Run Code Online (Sandbox Code Playgroud)
期望的正常输出:
ValueError: md5 sum does not match!
Run Code Online (Sandbox Code Playgroud)
这是一个测试脚本:https://gist.github.com/maphew/e3a75c147cca98019cd8
Reu*_*ani 61
简短的方法是使用该sys
模块并使用此命令:
sys.tracebacklimit = 0
Run Code Online (Sandbox Code Playgroud)
使用您的标志来确定行为.
例:
>>> import sys
>>> sys.tracebacklimit=0
>>> int('a')
ValueError: invalid literal for int() with base 10: 'a'
Run Code Online (Sandbox Code Playgroud)
更好的方法是使用和异常钩子:
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
Run Code Online (Sandbox Code Playgroud)
如果您仍然需要选择回落到原始钩子:
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)
Run Code Online (Sandbox Code Playgroud)
现在您可以将调试挂钩传递给处理程序,但您很可能希望始终使用源自的处理程序sys.excepthook
(因此不会传递任何内容debug_hook
).Python 在定义时间(常见陷阱...)中绑定默认参数一次,这使得它在替换之前始终使用相同的原始处理程序.
try:
pass # Your code here
except Exception as e:
if debug:
raise # re-raise the exception
# traceback gets printed
else:
print("{}: {}".format(type(e).__name__, e))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23012 次 |
最近记录: |