The following snippet:
import tracebackdef a():b()def b():try:c()except:traceback.print_exc()def c():assert Falsea()
Produces this output:
Traceback (most recent call last):File "test.py", line 8, in bc()File "test.py", line 13, in cassert False
AssertionError
What should I use if I want the complete stack trace including the call to a?
If it matters I have Python 2.6.6
edit: What I'd like to get is the same information I'd get if I left the try except out and let the exception propagate to the top level. This snippet for example:
def a():b()def b():c()def c():assert Falsea()
Produces this output:
Traceback (most recent call last):File "test.py", line 10, in <module>a()File "test.py", line 2, in ab()File "test.py", line 5, in bc()File "test.py", line 8, in cassert False
AssertionError
Here's a function based on this answer. It will also work when no exception is present:
def full_stack():import traceback, sysexc = sys.exc_info()[0]stack = traceback.extract_stack()[:-1] # last one would be full_stack()if exc is not None: # i.e. an exception is presentdel stack[-1] # remove call of full_stack, the printed exception# will contain the caught exception caller insteadtrc = 'Traceback (most recent call last):\n'stackstr = trc + ''.join(traceback.format_list(stack))if exc is not None:stackstr += ' ' + traceback.format_exc().lstrip(trc)return stackstr
print full_stack()
will print the full stack trace up to the top, including e.g. IPython's interactiveshell.py
calls, since there is (to my knowledge) no way of knowing who would catch exceptions. It's probably not worth figuring out anyway...
If print full_stack()
is called from within an except
block, full_stack
will include the stack trace down to the raise
. In the standard Python interpreter, this will be identical to the message you receive when not catching the exception (Which is why that del stack[-1]
is there, you don't care about the except
block but about the try
block).