假设您有这样的设置:
def a():
b()
def b():
c()
def c():
d()
def d():
e()
尝试调用a()
将导致以下回溯:
Traceback (most recent call last):
File "<pyshell#181>", line 1, in <module>
a()
File "<pyshell#87>", line 2, in a
b()
File "<pyshell#90>", line 2, in b
c()
File "<pyshell#93>", line 2, in c
d()
File "<pyshell#96>", line 2, in d
e()
NameError: name 'e' is not defined
是否有任何方法格式化异常,以便它只包括跟踪中的最后一个n
帧?例如,如果n = 2
,则回溯看起来像这样:
Traceback (most recent call last):
File "<pyshell#93>", line 2, in c
d()
File "<pyshell#96>", line 2, in d
e()
NameError: name 'e' is not defined
我对它做了一些修改,但还是没有办法。
从Python 3.5开始,traceback模块中的函数支持负限制(最初的提案是由您的问题启发并由Guido批准的):
import traceback
n = 2
try:
a()
except:
traceback.print_exc(limit=-n) # `n` last traceback entries
输出Traceback (most recent call last):
File "/home/vaultah/test.py", line 8, in c
d()
File "/home/vaultah/test.py", line 11, in d
e()
NameError: name 'e' is not defined
即使使用旧版本的Python
,也可以复制此行为import sys, traceback
n = 2
try:
a()
except:
ex = traceback.format_exception(*sys.exc_info())
sys.stderr.write(''.join([ex[0]] + ex[-n-1:]))
# or print(*[ex[0]] + ex[-n-1:], sep='', end='', file=sys.stderr)
输出将完全相同
traceback模块有许多函数,可以帮助您实现您正在寻找的功能。特别地,许多函数
的限制选项import traceback
def d():
c()
def c():
b()
def b():
a()
def a():
print traceback.extract_stack(limit=1)
d()
将返回一个元组,表示最后一个调用