views:

520

answers:

3

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.

+2  A: 

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.

AndiDog
A: 

traceback is enough - and I suppose that documentation describes it rather good. Simplified example:

import sys
import traceback

try:
    eval('a')
except NameError:
    traceback.print_exc(file=sys.stdout)
Dmitry Kochkin
I'm not trying to print the traceback. I'm trying to inspect it. How does this tell me whether the exception occurred in the eval text itself, or in a function called by the evaluated text?
Nick Retallack
SyntaxError will be thrown if `eval` text is wrong.
Dmitry Kochkin
Many different kinds of errors can be thrown if the eval text is wrong. I ended up using inspect and looking at the depth of the traceback to see if the error was caused by evaluating the original text, or if it was in the body of a called function.
Nick Retallack
A: 

In addition to AndiDog's answer about inspect, note that pdb lets you navigate up and down the stack, inspecting locals and such things. The source in the standard library pdb.py could be helpful to you in learning how to do such things.

Peter Hansen