您的位置:首页 > 编程语言 > Python开发

python exec/eval/execfile

2014-04-18 19:52 323 查看
eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果。

同样地, exec语句将字符串str当成有效Python代码来执行.提供给exec的代码的名称空间和exec语句的名称空间相同.

最后,execfile(filename [,globals [,locals ]])函数可以用来执行一个文件,看下面的例子:

>>> eval('3+4')

7

>>> exec 'a=100'

>>> a

100

>>> execfile(r'c:\test.py')

hello,world!

>>>

默认的,eval(),exec,execfile()所运行的代码都位于当前的名字空间中. eval(), exec,和 execfile()函数也可以接受一个或两个可选字典参数作为代码执行的全局名字空间和局部名字空间. 例如:

1 globals = {'x': 7,

2 'y': 10,

3 'birds': ['Parrot', 'Swallow', 'Albatross']

4 }

5 locals = { }

6

7 # 将上边的字典作为全局和局部名称空间

8 a = eval("3*x + 4*y", globals, locals)

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: