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


猜你喜欢
- 1.软件环境Windows10 教育版64位Python 3.6.32.问题描述我们在定义一个函数或者是调用一个函数的时候,总是希望能够知道
- 1._thread.start_new_thread(了解)import threadingimport timeimport _threa
- 本文实例讲述了mysql 设置自动创建时间及修改时间的方法。分享给大家供大家参考,具体如下:第一种,通过ddl进行定义CREATE TABL
- 昨晚在往MySQL数据库中插入一组数据时,出错了!数据库无情了给我报了个错误:ERROR 1365(22012):Division by 0
- 新手在配置pytorch过程中总会或多或少遇到些问题,同时网上关于pytorch的环境配置琳琅满目,不知道应该按照哪个配置,这里笔者记录一下
- 当我们使用电脑的时候,不可避免的会碰到重复点击的任务。所以我们可以使用python制作一个简单的连点器进行使用,同时可以提升写代码的水平。第
- 日期和时间类型MySQL有多个表示各种日期和时间值的数据类型, 比如YEAR和DATE. MySQL存储时间的最精确粒度是秒。 然而, 能做
- 1. pyecharts 模块介绍Echarts 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。
- 很多朋友在论坛和留言区域问mysql在什么情况下才需要进行分库分表,以及采用何种设计方式才是最优的选择,根据这些问题,小编为大家整理了关于M
- 误区 #1:在服务器故障转移后,正在运行的事务继续执行 这当然是错误的! 每次故障转移都伴随着某种形式的恢复。但是如果当正在执行的事务没有C
- 说明之前下载来zip包的漫画,里面的图片都是两张一起的:但是某些漫画查看软件不支持自动分屏,看起来会比较不舒服,所以只能自己动手来切分。操作
- 简介:with是从Python2.5引入的一个新的语法,它是一种上下文管理协议,目的在于从流程图中把 try,except 和finally
- 1、去官网下载1.1、网址:https://www.jetbrains.com/pycharm/ 点这里进入选择版本页面1.2、如果就是我们
- 这篇论坛文章(赛迪网技术社区)详细的介绍了在MySQL中使用GRANT语句增添新用户的具体步骤,更多内容请参考下文…&
- Python的装饰器可以实现在代码运行期间修改函数的上下文, 即可以定义函数在执行之前进行何种操作和函数执行后进行何种操作, 而函数本身并没
- 为新项目写的一份规范文档, 分享给大家. 我想前端开发过程中, 无论是团队开发, 还是单兵做站, 有一份开发文档做规范, 对开发工作都是很有
- Mako是一个高性能的Python模板库,它的语法和API借鉴了很多其他的模板库,如Django、Jinja2等等。基本用法创建模板并渲染它
- 结论:copy复制会比等号复制慢。但是copy复制为值复制,改变原切片的值不会影响新切片。而等号复制为指针复制,改变原切片或新切片都会对另一
- // 涉及命名空间 using System; using System.Collections; using System.Compone
- 1 问题描述最近与诸位聊起,在用户体验网站产品、完成任务的过程中,页面的切换到底是新开窗口,还是当前页面跳转,哪一种是最佳的用户体验。这一讨