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

bou*_*n21 1 python debugging function 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"
Run Code Online (Sandbox Code Playgroud)

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

unu*_*tbu 5

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

frame = inspect.currentframe().f_back
Run Code Online (Sandbox Code Playgroud)

并访问其当地人和全局有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"
Run Code Online (Sandbox Code Playgroud)

既然Y可能是一个变量,也许让用户按Enter下来打破循环.