【问题标题】:Python display custom error message / traceback on every exceptionPython 在每个异常上显示自定义错误消息/回溯
【发布时间】:2020-11-03 23:30:02
【问题描述】:

Python 是否支持为每个异常/引发/断言显示相同的自定义错误消息(无论代码在哪里中断)?

我目前对它的破解使用了一个装饰器。我有一个函数main,它可以很好地显示回溯,但我希望它每次抛出任何错误时也打印my_var(在函数范围内)。所以很明显这有一个范围问题——这只是为了说明我想要做什么。任何想法表示赞赏。

import traceback

def exit_with_traceback(func, *args, **kwargs):
    def wrap(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            # how do I get this to print my_var AND the traceback?
            print(traceback.format_exc())
    return wrap
        
@exit_with_traceback
def main(bar=1):
    my_var = 'hello world'  # variable specific to main()
    return bar + 1

main(bar=None)  # run main() to throw the exception

【问题讨论】:

    标签: python python-3.x error-handling python-decorators traceback


    【解决方案1】:

    您可以尝试覆盖sys 模块中的excepthook 函数。从其文档中:

    当异常被引发但未被捕获时,解释器调用 sys.excepthook 带三个参数,异常类,异常 实例和回溯对象。

    所以代码可能看起来像这样(我用过你的例子):

    import sys
    
    
    # define custom exception hook
    def custom_exception_hook(exc_type, value, traceback):
        print('Custom exception hook')
        print('Type:', exc_type)
        print('Value:', value)
        print('Traceback:', traceback)
        lc = traceback.tb_next.tb_frame.f_locals
        print(lc.get('my_var'))  # this prints "hello world"
    
    
    # override the default exception hook
    sys.excepthook = custom_exception_hook
    
    
    def main(bar=1):
        my_var = 'hello world'  # variable specific to main()
        return bar + 1
    
    
    main(bar=None)  # run main() to throw the exception
    

    sys.excepthook 的覆盖在 IDLE 中不起作用,但在命令行中可以正常工作。希望这会有所帮助。

    【讨论】:

    • 这与我的想法很接近,但不会打印出我在异常中想要的 my_var 的值。
    • 在回溯中查找局部变量怎么样?例如这样的事情(我尝试了特定的示例代码):“traceback.tb_next.tb_frame.f_locals”
    • 这是一种可行的方法。我已编辑您的解决方案并接受了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多