ev
同样地, exec语句将字符串str当成有效Python代码来执行.提供给exec的代码的名称空间和exec语句的名称空间相同.
最后,execfile(filename [,globals [,locals ]])函数可以用来执行一个文件,看下面的例子:
>>> ev
7
>>> exec 'a=100'
>>> a
100
>>> execfile(r'c:\test.py')
hello,world!
>>>
默认的,ev
1 globals = {'x': 7,
2 'y': 10,
3 'birds': ['Parrot', 'Swallow', 'Albatross']
4 }
5 locals = { }
6
7 # 将上边的字典作为全局和局部名称空间
8 a = ev
9 exec "for b in birds: print b" in globals, locals # 注意这里的语法
10 execfile("foo.py", globals, locals)
如果你省略了一个或者两个名称空间参数,那么当前的全局和局部名称空间就被使用.如果一个函数体内嵌嵌 套函数或lambda匿名函数时,同时又在函数主体中使用exec或execfile()函数时, 由于牵到嵌套作用域,会引发一个SyntaxError异常.
https://docs.python.org/2/library/functions.html?highlight=getattr#eval
The arguments are a Unicode or Latin-1 encoded string and optionalglobals and locals. If provided, globals must be a dictionary.If provided, locals can be any mapping object.
Changed in version 2.4: formerly locals was required to be a dictionary.
The expression argument is parsed and evaluated as a Python expression(technically speaking, a condition list) using the globals and localsdictionaries as global and local namespace. If the globals dictionary ispresent and lacks ‘__builtins__’, the current globals are copied into globalsbefore expression is parsed. This means that expression normally has fullaccess to the standard __builtin__ module and restricted environments arepropagated. If the locals dictionary is omitted it defaults to the globalsdictionary. If both dictionaries are omitted, the expression is executed in theenvironment where eval() is called. The return value is the result ofthe evaluated expression