Python使用eval函数执行动态标表达式过程详解
作者:lincappu 发布时间:2022-05-29 07:03:30
英文文档:
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 "<pyshell#3>", line 1, in <module>
eval('num + 2')
File "<string>", line 1, in <module>
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 "<pyshell#9>", line 1, in <module>
eval('abs(-1)',g)
File "<string>", line 1, in <module>
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__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num+2',{})
File "<string>", line 1, in <module>
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__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>>
来源:https://www.cnblogs.com/lincappu/p/8145344.html
猜你喜欢
- 本文实例讲述了python实现爬取千万淘宝商品的方法。分享给大家供大家参考。具体实现方法如下:import timeimport level
- 如果用户查询时,使用Order BY排序语句指定按员工编号来排序,那么排序后产生的所有记录就是临时数据。对于这些临时数据,Oracle数据库
- 虽然现在的GMail已经看不到这个效果,但之前那个可爱的深红色Loading仍然让许多人喜爱。我也将这款效果融入了我自己的WordPress
- 我们在使用很多新闻系统的时候,都会发现一个问题,尤其是使用 HtmlEdit 从WORD文档中直接拷贝文章(尤其里面有复杂表格和文字)的时候
- 引言委托 和 事件在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易。它们就
- 本文实例讲述了php查询mysql数据库并将结果保存到数组的方法。分享给大家供大家参考。具体分析如下:这里主要用到了mysql_fetch_
- 在html中关于select元素的问题在很多地方都提出过,而在前段时间的项目中,刚好遇到了关于select元素的两个小问题,这里进行一下总结
- 1000块钱做个百度?能提出这种要求的客户实乃乙方克星、民族之光、科创永动机、西虹市一大杰出青年,诺奖永远得不到的人才。但作为一个硬核的程序
- Django中提供了一个类Paginator专门用来管理和处理分页数据,所以我们在使用之前先导入好相应的类,,另外这里我们也导入了待会会用到
- 目前lnmp一键安装包比较多的问题就是502 Bad Gateway,大部分情况下原因是在安装php前,脚本中某些lib包可能没有安装上,造
- 在Windows vista之前的微软操作系统的地址栏与浏览器的地址栏是一样的,也是面包屑般的自上而下的线性等级形,如果想从D盘跳到C盘是不
- 前言在开发工作中,我们经常需要用到日期与时间,如:作为日志信息的内容输出计算某个功能的执行时间用日期命名一个日志文件的名称记录或展示某文章的
- 用css属性选择器可以有选择性地对链接样式进行控制,如让所有的外部链接都加一个小图标来标识其是一外部链接。但用css有弊端: 1、只支持Fi
- 无意中看到以前在电脑上保存的一个html页面,关于div水平垂直居中的问题。如何实现div水平垂直居中呢?1.已知宽高度水平垂直居中posi
- 如何把程序打包为whl首先需要一个库:setuptools如果是conda环境的话,这个包是自带的,不需要另外安装。首先把需要打包的py文件
- 本文实例分析了Python中的对象,方法,类,实例,函数用法。分享给大家供大家参考。具体分析如下:Python是一个完全面向对象的语言。不仅
- 简介Go的标准包Container中包含了常用的容器类型,包括conatiner/list,container/heap,container
- 今天看到某人博客推荐了http://dragoninteractive.com/这个网站,貌似一些效果做的比较不错,于是打开了看看,不过还真
- 本文介绍了网页运行代码框(runCode), 复制代码框(copyCode), 保存代码框(saveCode),的实现方法。javascri
- 冷备份是数据库文件的物理备份,通常在数据库通过一个shutdown normal或shutdown immediate 命令正常关闭后进行。