python中eval函数怎么用_Python使用eval函数执行动态标表达式过程详解

本文详细介绍了Python内置函数eval()的工作原理和使用方法,包括其参数解释、执行环境设置以及注意事项。eval()函数可以解析并执行一个字符串作为Python表达式,返回表达式的结果。文章通过实例展示了如何利用globals()和locals()函数来控制执行环境,并提醒了限制内置模块访问的方法。此外,还提到了动态执行语句应使用exec()函数的情况。
摘要由CSDN通过智能技术生成

英文文档:

eval(expression, globals=none, locals=none)

the arguments are a string and optional globals and locals. if provided, globals must be a dictionary. if provided, localscan be any mapping object.

the expression argument is parsed and evaluated as a python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. if the globals dictionary is present and lacks ‘__builtins__', the current globals are copied into globals before expression is parsed. this means that expressionnormally has full access to the standard builtins module and restricted environments are propagated. if the localsdictionary is omitted it defaults to the globals dictionary. if both dictionaries are omitted, the expression is executed in the environment where eval() is called. the return value is the result of the evaluated expression. syntax errors are reported as exceptions. example:

>>> x = 1

>>> eval('x+1')

2

this function can also be used to execute arbitrary code objects (such as those created by compile()). in this case pass a code object instead of a string. if the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be none.

hints: dynamic execution of statements is supported by the exec() function. the globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

see ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

执行动态标表达式求值

说明:

1. 执行动态语句,返回语句执行的值。

>>> eval('1+2+3+4')

10

2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量。

>>> g = {'num':2}

>>> eval('num + 2') #num未定义

traceback (most recent call last):

file "", line 1, in

eval('num + 2')

file "", line 1, in

nameerror: name 'num' is not defined

>>> eval('num + 2',g) #g中有定义num,可执行

4

4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

>>> g = {'num1':2}

>>> l = {'num2':4}

>>> eval('num1+num2',g,l)

6

5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

>>> g = {}

>>> eval('abs(-1)',g)

1

>>> g = {'__builtins__':{}}

>>> eval('abs(-1)',g) #不能使用内置函数了

traceback (most recent call last):

file "", line 1, in

eval('abs(-1)',g)

file "", line 1, in

nameerror: name 'abs' is not defined

6. 当globals参数不提供是,python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

>>> num = 1

>>> eval('num+2')

3

>>> globals() #返回字典中含有num的key

{'__doc__': none, 'num': 1, '__package__': none, '__name__': '__main__', '__loader__': , '__spec__': none, '__builtins__': }

>>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数

traceback (most recent call last):

file "", line 1, in

eval('num+2',{})

file "", line 1, in

nameerror: name 'num' is not defined

>>> l = locals()

>>> eval('num+2',{},l) #locals参数含有num的key,能求值

3

>>> locals()

{'__doc__': none, 'l': {...}, 'num': 1, '__package__': none, '__name__': '__main__', '__loader__': , '__spec__': none, '__builtins__': }

>>>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值