我使用 traceback 模块,如下所示:
import traceback
try:
1 / 0
except Exception:
print traceback.format_exc()
这给出了以下输出:
Traceback (most recent call last):
File "<ipython-input-3-6b05b5b621cb>", line 2, in <module>
1 / 0
ZeroDivisionError: integer division or modulo by zero
如果代码从文件中运行,回溯将告诉错误发生的行和字符号:)
编辑:
容纳Habibutsu的评论:Yes, it's useful for printing, but when needed to get more info (for example function name) - not suitable
文档页面告诉您如何以编程方式提取跟踪:http://docs.python.org/2/library/traceback.html
从上面链接的页面:
>>> import traceback
>>> def another_function():
... lumberstack()
...
>>> def lumberstack():
... traceback.print_stack()
... print repr(traceback.extract_stack())
... print repr(traceback.format_stack())
...
>>> another_function()
File "<doctest>", line 10, in <module>
another_function()
File "<doctest>", line 3, in another_function
lumberstack()
File "<doctest>", line 6, in lumberstack
traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
('<doctest>', 3, 'another_function', 'lumberstack()'),
('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
[' File "<doctest>", line 10, in <module>\n another_function()\n',
' File "<doctest>", line 3, in another_function\n lumberstack()\n',
' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
traceback.extract_stack 的文档字符串与 traceback.extract_tb 的文档字符串相同
traceback.extract_tb(traceback[, limit])
返回最多限制“预处理”堆栈跟踪条目的列表
从 traceback 对象中提取 traceback。它对
堆栈跟踪的替代格式。如果省略limit或None,则全部
条目被提取。 “预处理”的堆栈跟踪条目是
四元组(文件名、行号、函数名、文本)表示
通常为堆栈跟踪打印的信息。文字是
去除了前导和尾随空格的字符串;如果源
不可用,它是无。