小编Dan*_*ner的帖子

Python eval(compile(...),sandbox),全局变量在沙箱中除非在def中,为什么?

考虑以下:

def test(s):
    globals()['a'] = s

sandbox = {'test': test}
py_str = 'test("Setting A")\nglobals()["b"] = "Setting B"'
eval(compile(py_str, '<string>', 'exec'), sandbox)

'a' in sandbox # returns False, !What I dont want!
'b' in sandbox # returns True, What I want
'a' in globals() # returns True, !What I dont want!
'b' in globals() # returns False, What I want
Run Code Online (Sandbox Code Playgroud)

我甚至不确定如何询问,但我希望函数的全局范围成为我打算运行它的环境,而不必在eval期间编译函数.这可能吗?

感谢您的任何意见

def test(s):
    globals()['a'] = s

sandbox = {}

# create a new version of test() that uses the …
Run Code Online (Sandbox Code Playgroud)

python scope eval sandbox

4
推荐指数
1
解决办法
2561
查看次数

标签 统计

eval ×1

python ×1

sandbox ×1

scope ×1