当前位置:嗨网首页>书籍在线阅读

03-取得回溯字符串

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

11.2 取得回溯字符串

如果Python遇到错误,它就会生成一些错误信息,称为“回溯”。回溯包含了错误信息、导致该错误的代码行号,以及导致该错误的函数调用的序列。这个序列称为“调用栈”。

在Mu中打开一个新的文件编辑器窗口,输入以下程序,并将其保存为errorExample.py:

def spam():
    bacon()
def bacon():
    raise Exception('This is the error message.') 
spam()

如果运行errorExample.py,输出结果看起来像这样:

Traceback (most recent call last):
  File "errorExample.py", line 7, in <module> 
    spam()
  File "errorExample.py", line 2, in spam 
    bacon()
File "errorExample.py", line 5, in bacon
  raise Exception('This is the error message.') 
Exception: This is the error message.

根据回溯,可以看到该错误发生在第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')
...           errorFile.write(traceback.format_exc())
...           errorFile.close()
...           print('The traceback info was written to errorInfo.txt.')
111
The traceback info was written to errorInfo.txt.

write() 方法的返回值是111,因为有111个字符被写入文件中。回溯文本被写入errorInfo.txt:

Traceback (most recent call last):
  File "<pyshell#28>", line 2, in <module> 
Exception: This is the error message.

在11.4节“日志”中,你将学习如何使用 logging 记录模块,使用该模块比简单地将这个错误信息写入文本文件更有效。