How to get a complete exception stack trace in Python

2024/11/19 1:50:30

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
Answer

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).

https://en.xdnf.cn/q/26495.html

Related Q&A

python - should I use static methods or top-level functions

I come from a Java background and Im new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated …

Draw graph in NetworkX

Im trying to draw any graph in NetworkX, but get nothing, not even errors:import networkx as nx import matplotlib.pyplot as plt g1=nx.petersen_graph() nx.draw(g1)

Django 1.7 migrations wont recreate a dropped table, why?

Using Django 1.7 migrations.I accidentally dropped a table in my database. I assumed that by running migration again this would recreate the table but no, Django states "No migrations to apply&quo…

Reset ipython kernel

I was wondering if there is a way to restart the ipython kernel without closing it, like the kernel restart function that exists in the notebook. I tried %reset but that doesnt seem to clear the import…

What is the best way to remove a dictionary item by value in python? [duplicate]

This question already has answers here:Removing entries from a dictionary based on values(4 answers)Closed 4 years ago.I wonder if there is simple way to remove one or more dictionary element(s) from a…

How do I run a Python script on my web server?

Ive just started learning Python, and Im pretty lost right now. I want to run my script on my server that is hosted through hosting24.com. Their FAQ says they support Python, but I have no clue where t…

How to create an OrderedDict in Python?

I tried to maintain the order of a Python dictionary, since native dict doesnt have any order to it. Many answers in SE suggested using OrderedDict.from collections import OrderedDictdomain1 = { "…

How to log error to file, and not fail on exception

I am downloading a file from the net, and it fails even though I am doing: for p in query:try:except IOError as e:print e;If there is an error, I want to log it, and then continue on with the next file…

Suggestions for Python debugging tools? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site …

How can you bundle all your python code into a single zip file?

It would be convenient when distributing applications to combine all of the eggs into a single zip file so that all you need to distribute is a single zip file and an executable (some custom binary tha…