Python 在每个异常上显示自定义错误消息/回溯

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

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

最佳答案

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

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object.


所以代码可能看起来像这样(我用过你的例子):
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 中不起作用,但在命令行中可以正常工作。希望这会有所帮助。

关于Python 在每个异常上显示自定义错误消息/回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898391/

相关文章:

python - ZipFile.testzip() 在 Python 2 和 Python 3 上返回不同的结果

python - 如何从字典列表转换为字典?

python - 如何在 Python 中模拟具有嵌套属性的对象?

python - 有没有比ffmpeg更合适的方式在Python中合并视频和音频文件?

python - 如何使用 pandas 返回前 10 个频繁列值?

ruby-on-rails-3 - Rails 3 向电子邮件发送错误

ruby-on-rails - Rails中特定于 Action 的异常处理程序HTML

python - 除了Python中的中断

python - 如何在python中一个接一个地运行两个进程

python - 将 python 中的参数传递给 c 可执行文件