def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
# spam()
通过反向跟踪,可以看到该错误发生在第5行,在 bacon()
函数中。这次特定的
bacon()
调用来自第2行,在 spam()
函数中,它又在第7行被调用的。
在从多个位置调用函数的程序中,调用栈就能确定哪次调用导致了错误。
只要抛出的异常没有被处理,Python就会显示反向跟踪。但也可以调用
traceback.format_exc()
,得到它的字符串形式。
如果希望得到异常的反向跟踪的信息,
但也希望 except
语句优雅地处理该异常,
这个函数就很有用。在调用该函数之前,
需要导入 Python 的 traceback
模块。
保存反向跟踪的内容
例如,不是让程序在异常发生时就崩溃, 可以将反向跟踪信息写入一个日志文件, 并让程序继续运行。稍后,在准备调试程序时, 可以检查该日志文件。在交互式环境中输入以下代码:
import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
print(errorFile.write(traceback.format_exc()))
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
185 The traceback info was written to errorInfo.txt.
write()
方法的返回值是 116
,因为 116
个字符被写入到文件中。
反向跟踪文本被写入 errorInfo.txt
。
!more errorInfo.txt
Traceback (most recent call last): File "/tmp/ipykernel_71/2929639785.py", line 3, in <module> raise Exception('This is the error message.') Exception: This is the error message.
注意上面的内容,在不同的平台相同的 Python 解释器环境中,结果可能会有所不同。