How can you programmatically inspect the stack trace of an exception in Python?
traceback
is enough - and I suppose that documentation describes it rather well. Simplified example:
import sysimport tracebacktry: eval('a')except NameError: traceback.print_exc(file=sys.stdout)
You can use the inspect module which has some utility functions for tracing. Have a look at the overview of properties of the frame objects.
I like the traceback module.
You can get a traceback object using sys.exc_info()
. Then you can use that object to get a list preprocessed list of traceback entries using traceback.extract_tb()
. Then you can get a readable list using traceback.format_list()
as follows:
import sysimport traceback, inspecttry: f = open("nonExistant file",'r')except: (exc_type, exc_value, exc_traceback) = sys.exc_info() #print exception type print exc_type tb_list = traceback.extract_tb(sys.exc_info()[2]) tb_list = traceback.format_list(tb_list) for elt in tb_list: print elt #Do any processing you need here.
See the sys Module: http://docs.python.org/library/sys.html
and the traceback Module: http://docs.python.org/library/traceback.html