这是一个Python的问题.
请考虑下面的Python代码:
def controlled_exec(code):
x = 0
def increment_x():
nonlocal x
x += 1
globals = {"__builtins__": {}} # remove every global (including all python builtins)
locals = {"increment_x": increment_x} # expose only the increment function
exec(code, globals, locals)
return x
我希望这个函数提供一个受控代码API,它只计算increment_x()
次调用的数量.我试过了,我得到了正确的行为.
# returns 2
controlled_exec("""\
increment_x()
increment_x()
""")
我认为这种做法不安全,但出于好奇心,我想知道.我可以通过controlled_exec(...)
执行代码,将x
设置为任意值(比如负值)吗?我该怎么做呢?