Python内置函数(20)——exec
英文文档:
exec(object[, globals[, locals]])- This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the
returnandyieldstatements may not be used outside of function definitions even within the context of code passed to theexec()function. The return value isNone. - In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
- If the globals dictionary does not contain a value for the key
__builtins__, a reference to the dictionary of the built-in modulebuiltinsis inserted under that key. That way you can control what builtins are available to the executed code by inserting your own__builtins__dictionary into globals before passing it toexec(). - Note
- The built-in functions
globals()andlocals()return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument toexec(). - Note
- The default locals act as described for function
locals()below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()returns. - 说明:
- 1. exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。
>>> eval('a=1+2') #执行语句报错
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
eval('a=1+2')
File "<string>", line 1
a=1+2
^
SyntaxError: invalid syntax
>>> exec('a=1+2') #执行语句
>>> a
3
2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。
3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量
>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> exec('num2 = num + 2',g)
>>> g['num']
2
>>> g['num2'] #收集了exec中定义的num2全局变量
4
4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量
>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> l = {'num2':3}
>>> type(l)
<class 'dict'>
>>> exec('''
num2 = 13
num3 = num + num2
''',g,l)
>>> l['num2'] #l中num2值已经改变
13
5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。
>>> g = {}
>>> exec('a = abs(-1)',g)
>>>
>>> g = {'__builtins__':{}}
>>> exec('a = abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
exec('a = abs(-1)',g)
File "<string>", line 1, in <module>
NameError: name 'abs' is not defined
6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。
>>> num = 1
>>> exec('num2 = num + 1')
>>> globals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'num2': 2, 'num': 1}
>>>
>>>
>>> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
exec('num2 = num + 1',{})
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> l = locals()
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>>
>>> exec('num3 = num + 1',{},l)#指定了globals参数,globals中无num变量,指定了locals变量,locals变量含有num变量 执行成功
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, 'num3': 2, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>>
Python内置函数(20)——exec的更多相关文章
- Python内置函数(62)——exec
英文文档: exec(object[, globals[, locals]]) This function supports dynamic execution of Python code. obj ...
- Python内置函数(20)——hex
英文文档: hex(x) Convert an integer number to a lowercase hexadecimal string prefixed with "0x" ...
- Python内置函数之exec()
exec(object[,gobals[,locals]])这个函数和eval()有相同的作用,用来做运算的. 区别是,exec()可以直接将运算结果赋值给变量对象,而eval()只能运算不能赋值. ...
- 【转】python 内置函数总结(大部分)
[转]python 内置函数总结(大部分) python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为 ...
- python内置函数,匿名函数
一.匿名函数 匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n ...
- python 内置函数总结(大部分)
python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为我们提供了68个内置函数.它们就是pytho ...
- lambda 表达式+python内置函数
#函数 def f1(a,b): retrun a+b #lambda方式,形参(a,b):返回值(a+b) f2=lambda a,b : a+b 在一些比较简单的过程计算就可以用lambda p ...
- Python内置函数(4)
Python内置函数(4) 1.copyright 交互式提示对象打印许可文本,一个列表贡献者和版权声明 2.credits 交互式提示对象打印许可文本,一个贡献者和版权声明的列表 3.delattr ...
- 学习过程中遇到的python内置函数,后续遇到会继续补充进去
1.python内置函数isinstance(数字,数字类型),判断一个数字的数字类型(int,float,comple).是,返回True,否,返回False2.python内置函数id()可以查看 ...
随机推荐
- Django----使用模板系统渲染博客页面、实现列表和详情页的跳转、前后跳转功能
.模板写法同Flask,可以参考之前的FLask-模板 .将之前的BootStrap静态页面中的数据使用模板写 <!DOCTYPE html> <html lang="en ...
- 把我坑惨的一个update语句
最近好几次有开发同学在问我,比如下图: 问题归纳起来就是:在MySQL里面update一条记录,语法都正确的,但记录并没有被更新... 刚遇到这个问题的时候,我拿到这条语句直接在测试库里面执行了一把, ...
- scrapy递归解析和post请求
递归解析 递归爬取解析多页页面数据 每一个页面对应一个url,则scrapy工程需要对每一个页码对应的url依次发起请求,然后通过对应的解析方法进行作者和段子内容的解析. 实现方案: 1.将每一个页码 ...
- SQL语句练习题【主供自己学习、记忆】
1.这是我在面试中遇到的一道sql题,没有答出来,o(╥﹏╥)o 这是我刚才在网上查找函数之后写的SQL语句,能得到这个结果.[谁有不同的方法,欢迎底下评论留言哈] select (DATENAME( ...
- CodeForces - 777B Game of Credit Cards 贪心
题目链接: http://codeforces.com/problemset/problem/777/B 题目大意: A, B玩游戏,每人一串数字,数字不大于1000,要求每人从第一位开始报出数字,并 ...
- [POJ1193][NOI1999]内存分配(链表+模拟)
题意 时 刻 T 内存占用情况 进程事件 0 1 2 3 4 5 6 7 8 9 进程A申请空间(M=3, P=10)<成功> 1 A 2 A B 进程B申请空间(M=4, P=3)< ...
- SparkStreaming+Kafka整合
SparkStreaming+Kafka整合 1.需求 使用SparkStreaming,并且结合Kafka,获取实时道路交通拥堵情况信息. 2.目的 对监控点平均车速进行监控,可以实时获取交通拥堵情 ...
- hyperopt自动调参
hyperopt自动调参 在传统机器学习和深度学习领域经常需要调参,调参有些是通过通过对数据和算法的理解进行的,这当然是上上策,但还有相当一部分属于"黑盒" hyperopt可以帮 ...
- ORACLE启动报错ORA-03113: end-of-file on communication channel
使用过程中发现oracle运行很慢(其实应该先关注空间问题),就准备关机重启一下,关不掉就强制关闭,然后启动就报错了. 1.SQL> startup ORACLE instance starte ...
- 201771010126 王燕《面向对象程序设计(Java)》第十四周学习总结(测试程序11)
实验十四 Swing图形界面组件 理论部分: 不使用布局管理器 有时候可能不想使用任何布局管理器,而只 是想把组件放在一个固定的位置上.下面是将一 个组件定位到某个绝对定位的步骤: 1)将布局管理器 ...