传递所有当前变量以在python中运行

时间:2013-06-20 12:47:18

标签: python function debugging parameter-passing

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

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

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

2 个答案:

答案 0 :(得分:5)

使用CPython,您可以使用

找到呼叫者的框架
frame = inspect.currentframe().f_back

并使用frame.f_localsframe.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来突破循环。

答案 1 :(得分: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}