gpt4 book ai didi

python - 如何在函数中获取python异常回溯

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

我有一个应该处理所有错误的函数:

def err(e):
import traceback
message = traceback.print_exc()
print(message)

if __name__ == "__main__":
try:
1/0 # just sample
except Exception as e:
err(e)

但它返回一个简短的错误,如下所示:
integer division or modulo by zero
但是我需要更多详细信息( traceback)检查错误。

最佳答案

您正在将异常传递给函数,所以为什么要使用traceback,您在那里有了e;如果需要回溯,只需获取e.__traceback__即可:

import traceback

def err(e):
tb = e.__traceback__
# print traceback
traceback.print_tb(tb)

对于不依赖dunder的选项,可以使用 sys.exc_info并保留回溯:
import traceback, sys

def err(e):
*_, tb = sys.exc_info()
# print traceback
traceback.print_tb(tb)

关于python - 如何在函数中获取python异常回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380036/

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