Python内置函数(62)——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函数主要用于执行语句块。
第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。
>>> exec('print("你好")')
你好
>>> exec("print ('runoob.com')")
runoob.com
>>> exec ('for i in range(5):print("iter time: %d" % i)')
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
>>>
>>> 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.能够读取局部和全部变量,并且能修改全局变量,这个要注意的是,他修改完全局变量的值后,只能在内部使用因为没有 return 的功能,(eval 同理。)返回值永远是 None,
x=10
expr="z=30;sum=x+y+z;print(sum);print(x)"
y=20
exec(expr)
print(x,y,z)
exec(expr,{'x':1,'y':2,'z':1})
print(x,y)
exec(expr,{'x':0,'y':1,'z':0},{'x':0,'y':0,'z':1})
x=0
y=1
z=0
def expr():
x=0
y=0
z=1
z=30
sum=x+y+z
print(sum) expr()
3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量
>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> exec('num2 = num + 2',g)
>>> g['num']
2
>>> g['num2'] #收集了exec中定义的num2全局变量
4
4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量,如果该参数被忽略,那么它将会取与globals相同的值。
>>> 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()函数返回的字典去调用。
>>> 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}
>>>
8.命名空间,为了不影响全局的命名空间,可以指定命名空间。如果不适用builtins模块,需要在global添加一个key为__builtins__,value为{}的项。
a=2
scope={}
exec('a=4',scope)
dic=globals()
print(a)
print(scope['a'])
print(dic.keys())
print(dic.items())
print(scope.keys())
print(scope.items() # scope包含在 dic 里面 g={} # 指定空的__builtins__内置函数
print(g)
g= globals()
print(g)
exec('print(abs(-1))',g)
print(g.keys())
#
g={'__builtins__':{}}
exec('print(abs(-1))',{})
9. exec 里不能出现 break,continue等关键字,因为 exec 语句块是独立执行,不会和外部的代码进行交互。
i = 5
j = 7
n = 0
while n < i
print("looping")
exec('if j > 5;break')
n += 1
#报错:
looping
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<string>", line 3
SyntaxError: "break" outside loop
Python内置函数(62)——exec的更多相关文章
- Python内置函数(20)——exec
英文文档: exec(object[, globals[, locals]]) This function supports dynamic execution of Python code. obj ...
- Python内置函数之exec()
exec(object[,gobals[,locals]])这个函数和eval()有相同的作用,用来做运算的. 区别是,exec()可以直接将运算结果赋值给变量对象,而eval()只能运算不能赋值. ...
- Python内置函数(62)——sum
英文文档: sum(iterable[, start]) Sums start and the items of an iterable from left to right and returns ...
- Python | 内置函数(BIF)
Python内置函数 | V3.9.1 | 共计155个 还没学完, 还没记录完, 不知道自己能不能坚持记录下去 1.ArithmeticError 2.AssertionError 3.Attrib ...
- python 内置函数和函数装饰器
python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...
- Python 内置函数笔记
其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...
- 【转】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 ...
随机推荐
- CentOS 6.4 配置 Hadoop 2.6.5
(以下所有文件:点此链接 里面还有安装的视频教学,我这里是亲测了一次,如有报错请看红色部分.实践高于理论啊兄弟们!!) 一.安装CentOS 6.4 在VMWare虚拟机上,我设置的用户是hadoop ...
- 面向对象设计模式_生成器模式详解(Builder Pattern)
首先提出一个很容易想到应用场景: 手机的生产过程:手机有非常多的子件(部件),成千上万,不同品牌的手机的生产过程都是复杂而有所区别的,相同品牌的手机在设计上也因客户需求多样化,大到型号,小到颜色,是否 ...
- 原生js获取left值和top值
在用js做动态效果时,通常需要获取元素绝对定位中的left和top属性值.比如做一个碰撞广告,就要不停的获取元素的top和left属性值. 需要注意的事:取值的元素必须要设置position:abso ...
- curl post请求总是返回417错误
在进行post请求的时候, curl总是返回417错误 在使用curl做POST的时候, 当要POST的数据大于1024字节的时候, curl并不会直接就发起POST请求, 而是会分为俩步. 发送一个 ...
- Spring OAuth2 GitHub 自定义登录信息
# 原因 最近在做一款管理金钱的网站进行自娱自乐,发现没有安全控制岂不是大家都知道我的工资了(一脸黑线)? 最近公司也在搞 Spring OAuth2,当时我没有时间(其实那时候不想搞)就没做,现在回 ...
- 基于I2C总线的MPU6050学习笔记
MPU6050学习笔记 1. 简述 一直想自己做个四轴飞行器,却无从下手,终于狠下决心,拿出尘封已久的MPU6050模块,开始摸索着数据手册分析,一步一步地实现了MPU6050模块的功能,从MPU60 ...
- USB协议基础知识笔记
usb协议 功能层: 控制传输.中断传输.块传输(批量传输).同步传输 设备层:管理USB设备.分配地址.读取设备描述符 总线接口层:采用NRZI编码-反向非归零编码(0将前一个电平翻转,1不翻转) ...
- JAVAEE——BOS物流项目08:配置代理对象远程调用crm服务、查看定区中包含的分区、查看定区关联的客户
1 学习计划 1.定区关联客户 n 完善CRM服务中的客户查询方法 n 在BOS项目中配置代理对象远程调用crm服务 n 调整定区关联客户页面 n 实现定区关联客户 2.查看定区中包含的分区 n 页面 ...
- React简明学习
前面的话 React让组件化成为了前端开发的基本思路,比传统思路可以更好的控制前端复杂度,旧的开发方法受到了影响,如分离式的HTML/CSS.非侵入式JS.模板语言.MVC.CSS文件.Bootstr ...
- Vmware虚拟机不能使用键盘的解决方法
有个笔记本thinkpad T440要重装系统,但又怕前面的资料丢失,因此打算直接将整个物理机迁移到VCenter 6.5上去,比GHOST什么的方便多了,利用Vmware Convert工具直接在线 ...