exec声明:
exec code [ in globals[, locals]]
当我在python中执行以下代码时,结果让我很困惑。一些变量被设置到全局变量中,一些变量被设置到本地变量中。
s = """
# test var define
int_v1 = 1
list_v1 = [1, 2, 3]
dict_v1 = {1: 'hello', 2:'world', 3:'!'}
# test built-in function
list_v2 = [float(x) for x in list_v1]
len_list_v1 = len(list_v1)
# test function define
def func():
global g_var, list_v1, dict_v1
print 'access var in globals:'
print g_var
print 'access var in locals:'
for x in list_v1:
print dict_v1[x]
"""
g = {'__builtins__': __builtins__, 'g_var': 'global'}
l = {}
exec s in g, l
print 'globals:', g
print 'locals:', l
exec 'func()' in g, l
python2.6.5中的结果:
globals: {'__builtins__': <module '__builtin__' (built-in)>, 'dict_v1': {1: 'hello', 2: 'world', 3: '!'}, 'g_var': 'global', 'list_v1': [1, 2, 3]}
locals: {'int_v1': 1, 'func': <function func at 0x00ACA270>, 'x': 3, 'len_list_v1': 3, 'list_v2': [1.0, 2.0, 3.0]}
access var in globals:
global
access var in locals:
hello
world
!
如果我想将所有变量和函数设置到本地,并保留访问全局变量的权限。怎么办?
答案 0 :(得分:1)
我将把它留在这里:
>>> code = "a_bad_idea.func_globals['__builtins__'].open.__doc__"
>>> print eval(code, {}, {'a_bad_idea': lambda: None})
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
答案 1 :(得分:0)
我认为脚本应该作为闭包执行,但事实并非如此。
在脚本执行时,似乎会执行新的上下文。
根据LEGB规则,封装范围没有任何内容,因此脚本中的函数永远不能访问exec语句中的本地dict。