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编程-将Python程序转化为可执行程序[整理]
Apr 09 Python
闭包在python中的应用之translate和maketrans用法详解
Aug 27 Python
Python使用Matplotlib实现雨点图动画效果的方法
Dec 23 Python
python用户评论标签匹配的解决方法
May 31 Python
python 异或加密字符串的实例
Oct 14 Python
对pytorch网络层结构的数组化详解
Dec 08 Python
Python with关键字,上下文管理器,@contextmanager文件操作示例
Oct 17 Python
Python中base64与xml取值结合问题
Dec 22 Python
Python Pickle 实现在同一个文件中序列化多个对象
Dec 30 Python
Python 爬取必应壁纸的实例讲解
Feb 24 Python
在django项目中导出数据到excel文件并实现下载的功能
Mar 13 Python
如何利用python实现列表嵌套字典取值
Jun 10 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读取javascript设置的cookies的代码
2010/04/12 PHP
如何实现浏览器上的右键菜单
2006/07/10 Javascript
一个判断email合法性的函数[非正则]
2008/12/09 Javascript
24款热门实用的jQuery插件推荐
2014/12/24 Javascript
浅谈js构造函数的方法与原型prototype
2016/07/04 Javascript
详解vue2.0+axios+mock+axios-mock+adapter实现登陆
2018/07/19 Javascript
bootstrap table列和表头对不齐的解决方法
2019/07/19 Javascript
vue自定义表单生成器form-create使用详解
2019/07/19 Javascript
Vuex模块化应用实践示例
2020/02/03 Javascript
js 压缩图片的示例(只缩小体积,不更改图片尺寸)
2020/10/21 Javascript
python使用正则搜索字符串或文件中的浮点数代码实例
2014/07/11 Python
Python实现通过文件路径获取文件hash值的方法
2017/04/29 Python
详解Python实现多进程异步事件驱动引擎
2017/08/25 Python
python http接口自动化脚本详解
2018/01/02 Python
利用Python写一个爬妹子的爬虫
2018/06/08 Python
python实现俄罗斯方块
2018/06/26 Python
python高效过滤出文件夹下指定文件名结尾的文件实例
2018/10/21 Python
python3 实现对图片进行局部切割的方法
2018/12/05 Python
对python捕获ctrl+c手工中断程序的两种方法详解
2018/12/26 Python
Django在admin后台集成TinyMCE富文本编辑器的例子
2019/08/09 Python
numpy np.newaxis 的实用分享
2019/11/30 Python
PyCharm 无法 import pandas 程序卡住的解决方式
2020/03/09 Python
python实现企业微信定时发送文本消息的示例代码
2020/11/24 Python
Python更改pip镜像源的方法示例
2020/12/01 Python
python上下文管理的使用场景实例讲解
2021/03/03 Python
css3实现的多级渐变下拉菜单导航效果代码
2015/08/31 HTML / CSS
澳洲网红粉泥面膜:Sand & Sky
2019/08/13 全球购物
应用化学专业本科生求职信
2013/09/29 职场文书
工程造价专业大专生求职信
2013/10/06 职场文书
个人简历自荐信
2013/12/05 职场文书
洗煤厂厂长岗位职责
2014/01/03 职场文书
初中政治教学反思
2014/01/17 职场文书
销售经理竞聘书
2014/03/31 职场文书
人口与计划生育目标管理责任书
2014/07/29 职场文书
MySQL定时备份数据库(全库备份)的实现
2021/09/25 MySQL
Java Lambda表达式常用的函数式接口
2022/04/07 Java/Android