pythonexception

For python is there a way to print variables scope from context where exception happens?


Is there a way to print variables scope from context where exception happens?

For example:

def f():
    a = 1
    b = 2
    1/0

try:
    f()
except:
    pass # here I want to print something like "{'a': 1, 'b': 2}"

Solution

  • You can use the function sys.exc_info() to get the last exception that occurred in the current thread in you except clause. This will be a tuple of exception type, exception instance and traceback. The traceback is a linked list of frame. This is what is used to print the backtrace by the interpreter. It does contains the local dictionnary.

    So you can do:

    import sys
    
    def f():
        a = 1
        b = 2
        1/0
    
    try:
        f()
    except:
        exc_type, exc_value, tb = sys.exc_info()
        if tb is not None:
            prev = tb
            curr = tb.tb_next
            while curr is not None:
                prev = curr
                curr = curr.tb_next
            print prev.tb_frame.f_locals