>>> from env_helper import info; info()
页面更新时间: 2022-03-23 09:07:11
运行环境:
Linux发行版本: Debian GNU/Linux 11 (bullseye)
操作系统内核: Linux-5.10.0-11-amd64-x86_64-with-glibc2.31
Python版本: 3.9.2
12.2. 反向跟踪异常¶
这里介绍一下进行调试的技巧。
12.2.1. 在Python中反向跟踪异常¶
如果Python遇到错误,它就会生成一些错误信息,称为“反向跟踪”。 反向跟踪包含了出错消息、导致该错误的代码行号, 以及导致该错误的函数调用的序列。这个序列称为“调用栈”。
如以下程序 :
>>> def spam():
>>> bacon()
>>> def bacon():
>>> raise Exception('This is the error message.')
>>>
>>> spam()
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-1-f6c4cdc54dd2> in <module>
4 raise Exception('This is the error message.')
5
----> 6 spam()
<ipython-input-1-f6c4cdc54dd2> in spam()
1 def spam():
----> 2 bacon()
3 def bacon():
4 raise Exception('This is the error message.')
5
<ipython-input-1-f6c4cdc54dd2> in bacon()
2 bacon()
3 def bacon():
----> 4 raise Exception('This is the error message.')
5
6 spam()
Exception: This is the error message.
通过反向跟踪,可以看到该错误发生在第5行,在 bacon()
函数中。这次特定的 bacon()
调用来自第2行,在 spam()
函数中,它又在第7行被调用的。
在从多个位置调用函数的程序中,调用栈就能帮助你确定哪次调用导致了错误。
只要抛出的异常没有被处理,Python就会显示反向跟踪。但你也可以调用
traceback.format_exc()
,得到它的字符串形式。
如果你希望得到异常的反向跟踪的信息, 但也希望 except
语句优雅地处理该异常, 这个函数就很有用。在调用该函数之前, 需要导入
Python 的 traceback
模块。
12.2.2. 保存反向跟踪的内容¶
例如,不是让程序在异常发生时就崩溃, 可以将反向跟踪信息写入一个日志文件, 并让程序继续运行。稍后,在准备调试程序时, 可以检查该日志文件。在交互式环境中输入以下代码:
>>> 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.')
184
The traceback info was written to errorInfo.txt.
write()
方法的返回值是 116
,因为 116
个字符被写入到文件中。
反向跟踪文本被写入 errorInfo.txt
。
>>> !more errorInfo.txt
Traceback (most recent call last):
File "<ipython-input-2-3cfe0b89592c>", line 3, in <module>
raise Exception('This is the error message.')
Exception: This is the error message.
注意上面的内容,在不同的平台于 Python 解释器环境中,结果可能会有不同。