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/