Exception handling: Extracting local variables

In Python it is possible to go back one frame in a traceback to extract state information like local variables (adapted from example found here).

def f():

def fail_here():
        raise NotImplementedError, 'Error!'
    except Exception, e:
        import sys, traceback
        exc_type, exc_value, exc_tb = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_tb, limit=2)
        # get local variables from f()
        frame = exc_tb.tb_frame
        print frame.f_back.f_locals


This results in

Traceback (most recent call last):
  File "<stdin>", line 3, in fail_here
NotImplementedError: Error!
{'a': 3}

See also:

comments powered by Disqus