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 相关文章推荐
Flask数据库迁移简单介绍
Oct 24 Python
Python实现自动发送邮件功能
Mar 02 Python
python批量实现Word文件转换为PDF文件
Mar 15 Python
python 一个figure上显示多个图像的实例
Jul 08 Python
Django 实现xadmin后台菜单改为中文
Nov 15 Python
Python爬取爱奇艺电影信息代码实例
Nov 26 Python
你应该知道的Python3.6、3.7、3.8新特性小结
May 12 Python
详解向scrapy中的spider传递参数的几种方法(2种)
Sep 28 Python
Python lxml库的简单介绍及基本使用讲解
Dec 22 Python
python脚本定时发送邮件
Dec 22 Python
M1芯片安装python3.9.1的实现
Feb 02 Python
详解Python生成器和基于生成器的协程
Jun 03 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 SEO优化之URL优化方法
2011/04/21 PHP
PHP文件上传原理简单分析
2011/05/29 PHP
ThinkPHP的RBAC(基于角色权限控制)深入解析
2013/06/17 PHP
php实现发送微信模板消息的方法
2015/03/07 PHP
微信小程序发送订阅消息的方法(php 为例)
2019/10/30 PHP
Javascript获取当前时间函数和时间操作小结
2014/10/01 Javascript
JavaScript实现的简单烟花特效代码
2015/10/20 Javascript
JavaScript代码实现禁止右键、禁选择、禁粘贴、禁shift、禁ctrl、禁alt
2015/11/17 Javascript
轻松学习jQuery插件EasyUI EasyUI创建树形菜单
2015/11/30 Javascript
js确认框confirm()用法实例详解
2016/01/07 Javascript
JS 60秒后重新发送验证码的实例讲解
2017/07/26 Javascript
浅谈node的事件机制
2017/10/09 Javascript
layui中table表头样式修改方法
2018/08/15 Javascript
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
vue debug 二种方法
2018/09/16 Javascript
[03:17]2014DOTA2 国际邀请赛中国区预选赛 四强专访
2014/05/23 DOTA
python读写文件操作示例程序
2013/12/02 Python
Python下使用Psyco模块优化运行速度
2015/04/05 Python
Python统计文件中去重后uuid个数的方法
2015/07/30 Python
Python栈算法的实现与简单应用示例
2017/11/01 Python
示例详解Python3 or Python2 两者之间的差异
2018/08/23 Python
在python中只选取列表中某一纵列的方法
2018/11/28 Python
python如何解析配置文件并应用到项目中
2019/06/27 Python
卸载tensorflow-cpu重装tensorflow-gpu操作
2020/06/23 Python
Selenium python时间控件输入问题解决方案
2020/07/22 Python
matplotlib教程——强大的python作图工具库
2020/10/15 Python
python自动生成sql语句的脚本
2021/02/24 Python
2014领导班子正风肃纪思想汇报
2014/09/18 职场文书
六查六看自检自查剖析材料
2014/10/14 职场文书
2015年扫黄打非工作总结
2015/05/13 职场文书
学校中层领导培训心得体会
2016/01/11 职场文书
CSS几步实现赛博朋克2077风格视觉效果
2021/06/16 HTML / CSS
使用HttpSessionListener监听器实战
2022/03/17 Java/Android
【海涛DOTA解说】EVE女子战队独家录像加ZSMJ神牛两连发
2022/04/01 DOTA
Java 超详细讲解数据结构中的堆的应用
2022/04/02 Java/Android
python数字图像处理:图像简单滤波
2022/06/28 Python