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

标签 python error-handling user-experience

除非设置了详细或调试标志,否则隐藏回溯错误的惯用 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/

相关文章:

python - "Fork and Join"具有无服务器函数(例如 AWS Lambda)/Python

python - 从枚举中获取所有值,当值在 Python 3.7 中是可调用的

python - 自动注册新的级长流程?

vba - 如何从 VBA 中的函数返回错误对象?

html - 使用特定的 target_country 和国家元标记

python - 为什么三元条件不能完美地用于字符串连接

android - 处理 PocketSphinx Android 应用程序中的错误

python - “Rect argument is invalid”

JavaScript 在 <head> 中还是在 </body> 之前?

iphone - 在基于文档的应用程序中保存更改的用户界面注意事项