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

Accepted answer
Score: 21

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

So you can 1 do:

import sys

def f():
    a = 1
    b = 2

    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
Score: 7

You have to first extract traceback, in 4 your example something like this would print 3 it:

    print sys.exc_traceback.tb_next.tb_frame.f_locals

I'm not sure about the tb_next, I would 2 guess you have to go through the complete 1 traceback, so something like this (untested):

    tb_last = sys.exc_traceback
    while tb_last.tb_next:
        tb_last = tb_last.tb_next
    print tb_last.tb_frame.f_locals
Score: 3

Perhaps you're looking for locals() and globals()?


Score: 1

Depending on what you need, there are 2 4 general best practices.

Just print the variables with minimal code edits

Have a look at some 3 related packages. For simple usage you might 2 pick traceback-with-variables (pip install traceback-with-variables), here is it's postcard

enter image description here

Or try tbvaccine, or 1 better-exceptions, or any other package

Programmatically access variables to use them in your code

Use inspect module

except ... as ...:
    x = inspect.trace()[-1][0].f_locals['x']

More Related questions