如何确定引发了什么函数异常.例如,存在两个函数:'foo'和'bar'.在'foo'中,异常将随机提出.
import random
def foo():
if random.randint(1, 10) % 2:
raise Exception
bar()
def bar():
raise Exception
try:
foo()
except Exception as e:
print "Exception raised in %s" % ???
Run Code Online (Sandbox Code Playgroud)
import inspect
try:
foo()
except Exception as e:
print "Exception raised in %s" % inspect.trace()[-1][3]
Run Code Online (Sandbox Code Playgroud)
我使用回溯模块,如下所示:
import traceback
try:
1 / 0
except Exception:
print traceback.format_exc()
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
Traceback (most recent call last):
File "<ipython-input-3-6b05b5b621cb>", line 2, in <module>
1 / 0
ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
如果代码从文件运行,回溯将告诉错误发生位置的行号和字符号:)
编辑:
为了适应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']
Run Code Online (Sandbox Code Playgroud)
for 的文档字符串与 fortraceback.extract_stack相同traceback.extract_tb
traceback.extract_tb(traceback[, limit])
返回从回溯对象回溯中提取的最多限制“预处理”堆栈跟踪条目的列表。它对于堆栈跟踪的替代格式很有用。如果省略限制或无,则提取所有条目。“预处理”堆栈跟踪条目是一个四元组(文件名、行号、函数名称、文本),表示通常为堆栈跟踪打印的信息。文本是去除了前导和尾随空格的字符串;如果源不可用,则为 None。
| 归档时间: |
|
| 查看次数: |
1528 次 |
| 最近记录: |