python exec/eval/execfile

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值