隐藏回溯跟踪,除非有调试标志

2024-04-25 05:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: pymy标志matchlinenotcodeapt
2条回答
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))

简单的方法是使用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

编辑:

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

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在定义时间(常见陷阱…)中绑定默认参数一次,这使得在替换之前,它始终与同一原始处理程序一起工作。

相关问题 更多 >