C Python: Running Python code within a context

不问归期 提交于 2019-11-28 21:27:45

Python doesn't actually copy outer-scope locals into inner-scope locals; the documentation for locals states:

Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Here "free" variables refers to variables closed over by a nested function. It's an important distinction.

The simplest fix for your situation is just to pass the same dict object as globals and locals:

code = """
myvar = 300
def func():
    return myvar

func()
"""
d = {}
eval(compile(code, "<str>", "exec"), d, d)

Otherwise, you can wrap your code in a function and extract it from the compiled object:

s = 'def outer():\n    ' + '\n    '.join(code.strip().split('\n'))
exec(compile(s, '<str>', 'exec').co_consts[0], {}, {})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!