这是怎么回事?
global_function = """
x = "Hello World"
def print_global_x():
print(x)
print_global_x()
"""
exec(global_function, {"__builtins__": builtins})
但这个看似相同的例子不起作用?
import builtins
class TestEnvironment(dict):
pass
global_env = TestEnvironment()
global_env['__builtins__'] = builtins
exec(global_function, global_env)
第二个例子给出了一个错误,说x没有定义,但第一个工作完美。实际上,似乎第二个示例评估代码就像它被封装在类定义中一样,这是两个dict对象传递给exec函数的情况,如文档中所述。
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-edb1f5a14344> in <module>()
9 """
10
---> 11 exec(global_function, global_env)
<string> in <module>()
<string> in print_global_x()
NameError: name 'x' is not defined
答案 0 :(得分:1)