gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:09:12 29 4
gpt4 key购买 nike

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 callssys.excepthook with three arguments, the exception class, exceptioninstance, 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com