Formatting an exception in python to include all but the last 'n' traceback frames
Let's assume you had a setup like this:
def a():
b()
def b():
c()
def c():
d()
def d():
e()
Attempting to call a()
will result in the following trace:
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
Is there a way to format the exception so that it only includes the last frames n
in the trace? For example, if the n = 2
trace looks like this:
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
I've worked with it a bit and can't figure out how to do it.
source to share
As of Python 3.5, functions from the trace module support negative limits (original proposal was inspired by your question and approved by Guido):
import traceback
n = 2
try:
a()
except:
traceback.print_exc(limit=-n) # `n` last traceback entries
outputs
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
You can replicate this behavior even if you are using older 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)
The output will be exactly the same.
source to share
The traceback module has many features to help you achieve what you are looking for. In particular, the constraint options for many of these functions
import traceback
def d():
c()
def c():
b()
def b():
a()
def a():
print traceback.extract_stack(limit=1)
d()
Returns a tuple representing the last call to a
source to share