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 相关文章推荐
使用graphics.py实现2048小游戏
Mar 10 Python
分享Python文本生成二维码实例
Jan 06 Python
Python爬虫的两套解析方法和四种爬虫实现过程
Jul 20 Python
Python中Numpy mat的使用详解
May 24 Python
安装docker-compose的两种最简方法
Jul 30 Python
Python input函数使用实例解析
Nov 22 Python
Python实现将蓝底照片转化为白底照片功能完整实例
Dec 13 Python
python kafka 多线程消费者&amp;手动提交实例
Dec 21 Python
python 安装库几种方法之cmd,anaconda,pycharm详解
Apr 08 Python
Pyside2中嵌入Matplotlib的绘图的实现
Feb 22 Python
Python实现Hash算法
Mar 18 Python
Python线程池与GIL全局锁实现抽奖小案例
Apr 13 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
ThinkPHP和UCenter接口冲突的解决方法
2016/07/25 PHP
PHP中常用的三种设计模式详解【单例模式、工厂模式、观察者模式】
2019/06/14 PHP
按钮JS复制文本框和表格的代码
2011/04/01 Javascript
JQuery制作的放大效果的popup对话框(未添加任何jquery plugin)分享
2013/04/28 Javascript
jquery的ajax跨域请求原理和示例
2014/05/08 Javascript
批量修改标签css样式以input标签为例
2014/07/31 Javascript
js中实现多态采用和继承类似的方法
2014/08/22 Javascript
node+express+ejs制作简单页面上手指南
2014/11/26 Javascript
Javascript中实现String.startsWith和endsWith方法
2015/06/10 Javascript
关于Bootstrap弹出框无法调用问题的解决办法
2016/03/10 Javascript
JS中split()用法(将字符串按指定符号分割成数组)
2016/10/24 Javascript
一个炫酷的Bootstrap导航菜单
2016/12/28 Javascript
angularjs项目的页面跳转如何实现(5种方法)
2017/05/25 Javascript
详解利用 Vue.js 实现前后端分离的RBAC角色权限管理
2017/09/15 Javascript
JavaScript变量声明var,let.const及区别浅析
2018/04/23 Javascript
vue项目中公用footer组件底部位置的适配问题
2018/05/10 Javascript
Vue中的验证登录状态的实现方法
2019/03/09 Javascript
[53:43]VP vs NewBee Supermajor 胜者组 BO3 第三场 6.5
2018/06/06 DOTA
python 时间信息“2018-02-04 18:23:35“ 解析成字典形式的结果代码详解
2018/04/19 Python
Python 编码规范(Google Python Style Guide)
2018/05/05 Python
Python合并多个Excel数据的方法
2018/07/16 Python
对Python闭包与延迟绑定的方法详解
2019/01/07 Python
Django ImageFiled上传照片并显示的方法
2019/07/28 Python
解决Python安装cryptography报错问题
2020/09/03 Python
PyQt5结合matplotlib绘图的实现示例
2020/09/15 Python
Html5实现首页动态视频背景的示例代码
2019/09/25 HTML / CSS
浅析HTML5 Landmark
2020/09/11 HTML / CSS
Kenneth Cole官网:纽约时尚优雅品牌
2016/11/14 全球购物
合同专员岗位职责
2013/12/18 职场文书
2014年五一劳动节社区活动总结
2014/04/14 职场文书
国际商务英语专业求职信
2014/07/08 职场文书
银行主办会计岗位职责
2014/08/13 职场文书
2014年监理工作总结范文
2014/11/17 职场文书
公务员考察材料范文
2014/12/23 职场文书
离婚财产分割协议书
2015/08/11 职场文书
Python中os模块的简单使用及重命名操作
2021/04/17 Python