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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27674602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:07:19  来源:igfitidea点击:

Hide traceback unless a debug flag is set

pythonerror-handlinguser-experience

提问by matt wilkie

What is the idiomatic python way to hide traceback errors unless a verbose or debug flag is set?

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

Example code:

示例代码:

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

Existing output now, but only desired when called with foo.py --debug:

现在现有的输出,但只有在调用时才需要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!

Desired normal output:

所需的正常输出:

ValueError: md5 sum does not match!

Here's a test script: https://gist.github.com/maphew/e3a75c147cca98019cd8

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

采纳答案by Reut Sharabani

The short way is using the sysmodule and use this command:

简短的方法是使用sys模块并使用以下命令:

sys.tracebacklimit = 0

Use your flag to determine the behaviour.

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

Example:

例子:

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

The nicer way is to use and 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

Edit:

编辑:

If you still need the option of falling back to the original 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)

Now you can pass a debug hook to the handler, but you'll most likely want to always use the one originated in sys.excepthook(so pass nothing in debug_hook). Python binds default arguments oncein definition time (common pitfall...) which makes this always work with the same original handler, before replaced.

现在您可以将调试钩子传递给处理程序,但您很可能希望始终使用起源于的钩子sys.excepthook(因此不要在 中传递任何内容debug_hook)。Python在定义时绑定一次默认参数(常见陷阱...),这使得它在替换之前始终使用相同的原始处理程序。

回答by GingerPlusPlus

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))