When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I've looked at the traceback module, but I can't figure out how to use it.
My goal is to catch any exceptions that occur during the parsing of an eval expression, without catching exceptions thrown by any functions it may have called. Don't berate me for using eval. It wasn't my decision.
NOTE: I want to do this programmatically, not interactively.
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 usingtraceback.extract_tb()
. Then you can get a readable list usingtraceback.format_list()
as follows:See the sys Module: http://docs.python.org/library/sys.html
and the traceback Module: http://docs.python.org/library/traceback.html
You define such a function (doc here):
and call it from your modules so:
The function raiseErr will print info about the place you called it.
More elaborate, you can do so:
Other possibility is to define this function:
And call it in the place where you want the trace. If you want all the trace, make an iterator from 1 up in
_getframe(1)
.In addition to AndiDog's answer about
inspect
, note thatpdb
lets you navigate up and down the stack, inspecting locals and such things. The source in the standard librarypdb.py
could be helpful to you in learning how to do such things.traceback
is enough - and I suppose that documentation describes it rather well. Simplified example: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.