有没有办法教Python(3.x)显示异常的整个堆栈跟踪?例如:
def foo(n):
try:
1/n
except Exception as x:
return x
else:
return foo(n-1)
def bar(x):
raise x
bar(foo(3))
发射
Traceback (most recent call last):
File "/tmp/test.py", line 17, in <module>
bar(foo(3))
File "/tmp/test.py", line 15, in bar
raise x
File "/tmp/test.py", line 7, in foo
1/n
ZeroDivisionError: division by zero
不幸的是,foo()
的调用上下文被抑制了。将traceback.print_stack(x.__traceback__.tb_frame)
添加到bar()
打印
File "/tmp/test.py", line 18, in <module>
bar(foo(3))
File "/tmp/test.py", line 13, in foo
return foo(n-1)
File "/tmp/test.py", line 13, in foo
return foo(n-1)
File "/tmp/test.py", line 13, in foo
return foo(n-1)
File "/tmp/test.py", line 5, in foo
return x
表明信息不会丢失。我想说服Python在打印错误时包含这些行。