1

我想在 Python 中调用一个函数,该函数允许我在执行期间访问所有当前变量(用于调试)。像这样的东西:

def interruptWithTerminal():
    interruptchoice = ""
    while interruptchoice != "Y":
        interruptchoice = raw_input("print what variable? (Y to continue script): ")
        try:
            print eval(interruptchoice)
        except:
            print "Error"

我的问题是我在调用此函数时无法访问变量。有任何想法吗?

4

2 回答 2

5

使用 CPython,您可以找到调用者的框架

frame = inspect.currentframe().f_back

frame.f_locals并使用,和 访问其局部变量和全局变量frame.f_globals


import inspect
def interruptWithTerminal():
    frame = inspect.currentframe().f_back
    while True:
        interruptchoice = raw_input("print what variable? (Press Enter to continue): ")
        if not interruptchoice.strip(): break
        try:
            print eval(interruptchoice, frame.f_globals, frame.f_locals)
        except:
            print "Error"

由于Y可能是一个变量,也许让用户按下Enter以跳出循环。

于 2013-06-20T12:51:49.047 回答
0

像这样的东西?

>>> var = True
>>> import __main__ as main
>>> for attr in dir(main):
    print str(attr), '=', repr(getattr(main, attr))


__builtins__ = <module '__builtin__' (built-in)>
__doc__ = None
__name__ = '__main__'
__package__ = None
attr = 'attr'
main = <module '__main__' (built-in)>
var = True

您可以像这样制作所有变量的字典:

>>> var = True
>>> import __main__ as main
>>> d = {attr:getattr(main, attr) for attr in dir(main)}
>>> d
{'attr': 'var', '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'var': True, '__name__': '__main__', 'main': <module '__main__' (built-in)>, '__doc__': None}
于 2013-06-20T13:00:27.837 回答