Python使用eval函数执行动态标表达式过程详解


Posted in Python onOctober 17, 2020

英文文档:

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)>}
>>>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python字典的常用操作方法小结
May 16 Python
利用Python批量生成任意尺寸的图片
Aug 29 Python
python 与GO中操作slice,list的方式实例代码
Mar 20 Python
Python利用Beautiful Soup模块创建对象详解
Mar 27 Python
在django中使用自定义标签实现分页功能
Jul 04 Python
Python FTP两个文件夹间的同步实例代码
May 25 Python
Python二进制文件读取并转换为浮点数详解
Jun 25 Python
python科学计算之numpy——ufunc函数用法
Nov 25 Python
基于Python实现人脸自动戴口罩系统
Feb 06 Python
Python使用socket模块实现简单tcp通信
Aug 18 Python
matplotlib设置颜色、标记、线条,让你的图像更加丰富(推荐)
Sep 25 Python
python 带时区的日期格式化操作
Oct 23 Python
Python基于locals返回作用域字典
Oct 17 #Python
Python classmethod装饰器原理及用法解析
Oct 17 #Python
Python基于staticmethod装饰器标示静态方法
Oct 17 #Python
详解python算法常用技巧与内置库
Oct 17 #Python
Python 操作SQLite数据库的示例
Oct 16 #Python
python Selenium 库的使用技巧
Oct 16 #Python
用Python进行websocket接口测试
Oct 16 #Python
You might like
PHP date函数参数详解
2006/11/27 PHP
ueditor 1.2.6 使用方法说明
2013/07/24 PHP
PHP检测字符串是否为UTF8编码的常用方法
2014/11/21 PHP
PHP调用.NET的WebService 简单实例
2015/03/27 PHP
php遍历CSV类实例
2015/04/14 PHP
js获取字符串字节数方法小结
2015/06/09 Javascript
简单几步实现返回顶部效果
2016/12/05 Javascript
BootStrap 获得轮播中的索引和当前活动的焦点对象
2017/05/11 Javascript
JS 组件系列之Bootstrap Table的冻结列功能彻底解决高度问题
2017/06/30 Javascript
js图片放大镜实例讲解(必看篇)
2017/07/17 Javascript
深入理解Vue nextTick 机制
2018/04/28 Javascript
Vue中使用webpack别名的方法实例详解
2018/06/19 Javascript
vue自定义一个v-model的实现代码
2018/06/21 Javascript
快速解决vue动态绑定多个class的官方实例语法无效的问题
2018/09/05 Javascript
vue移动端项目缓存问题实践记录
2018/10/29 Javascript
vue-cli3中vue.config.js配置教程详解
2019/05/29 Javascript
Vue.js实现可编辑的表格
2019/12/11 Javascript
Vue开发环境跨域访问问题
2020/01/22 Javascript
Vue3.0的优化总结
2020/10/16 Javascript
Python有序查找算法之二分法实例分析
2017/12/11 Python
Python中optparser库用法实例详解
2018/01/26 Python
Python 数据处理库 pandas 入门教程基本操作
2018/04/19 Python
python中正则表达式 re.findall 用法
2018/10/23 Python
解决pycharm安装后代码区不能编辑的问题
2018/10/28 Python
python实现的批量分析xml标签中各个类别个数功能示例
2019/12/30 Python
python IDLE添加行号显示教程
2020/04/25 Python
Pytorch转tflite方式
2020/05/25 Python
Django Admin 上传文件到七牛云的示例代码
2020/06/20 Python
python 制作python包,封装成可用模块教程
2020/07/13 Python
python 制作磁力搜索工具
2021/03/04 Python
美国儿童珠宝在线零售商:Loveivy
2019/05/22 全球购物
餐饮商业计划书范文
2014/04/29 职场文书
祖国在我心中的演讲稿
2014/05/04 职场文书
社会体育专业大学生职业生涯规划书
2014/09/17 职场文书
小学老师对学生的评语
2014/12/29 职场文书
2015年医院保卫科工作总结
2015/07/23 职场文书