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
return
andyield
statements 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 modulebuiltins
is 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()可以查看 ...
随机推荐
- python--random库基本介绍
random库是使用随机数的Python标准库 python中用于生成伪随机数的函数库是random 因为是标准库,使用时候只需要import random random库包含两类函数,常用的共9个 ...
- windows7搜索python java go php等其他文件内容
1.添加文件内容搜索配置 2.将需要搜索的文件索引,添加至windows索引 控制面板->索引选项->高级->文件类型 把需要搜索的文件添加一下索引 3.如果不行的话,那么还是在索引 ...
- Linux服务器限制ssh登录,查看登录日志
网络上的服务器很容易受到攻击,最惨的就是被人登录并拿到root权限.有几个简单的防御措施: 1. 修改ssh服务的默认端口 ssh服务的默认端口是22,一般的恶意用户也往往扫描或尝试连接22端口.所以 ...
- The frist email to myself by python
昨天用python模块给自己发了第一封电子邮件,真是激动 今天完善了一下. code: import smtplib from email.mime.text import MIMEText//ema ...
- [POJ1961]Period (KMP)
题意 求字符串s的最小循环元长度和循环次数 思路 s[1~i]满足循环元要len能整除i并且s[len+1~i]=s[1~i-len] 代码 #include<cstdio> #inclu ...
- Helm 入门指南
Helm 为Kubernetes的软件包管理工具,Helm有两部分组成:Helm客户端.Tiller服务端,Helm三个主要部件:Chart.仓库.Release: Chart:为Kubernetes ...
- 关于在centos7 64为引用android so引发的问题修复
背景: 公司有解码的app,解码库位c++编写so动态库. 之前做过一版在调用html5摄像头,然后提取图像进行解码,后面因为图像质量不佳放弃. 最近 因为小程序api有更新 可以获取到相对清晰的图像 ...
- 做个流量站-聚茶吧, 汇聚"茶"的地方
犹豫了好久,终于下定决心,做一回个人站长了,虽然没啥经验,但毕竟也是IT科班出身了,准备用一年的事件摸索一下内容站和SEO,看看能否积累点经验,赚点小钱. 推酷-靠爬虫起家的内容站 做内容站,站长们都 ...
- dedecms给图片加水印覆盖整张图片
位置: /include/image.class.php $wmwidth = $imagewidth - $logowidth; $wmheight = $imageheight - $logohe ...
- Spring Security中html页面设置hasRole无效的问题
Spring Security中html页面设置hasRole无效的问题 一.前言 学了几天的spring Security,偶然发现的hasRole和hasAnyAuthority的区别.当然,可能 ...