开发者

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开发者_StackOverflow社区 like "{'a': 1, 'b': 2}"


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


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

except:
    print sys.exc_traceback.tb_next.tb_frame.f_locals

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

except:
    tb_last = sys.exc_traceback
    while tb_last.tb_next:
        tb_last = tb_last.tb_next
    print tb_last.tb_frame.f_locals


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


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

Just print the variables with minimal code edits

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

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

Or try tbvaccine, or 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']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜