龙空技术网

Python3.6内置函数(20)——exec()

数据之魅 259

前言:

当前小伙伴们对“exec函数”大致比较关注,朋友们都需要剖析一些“exec函数”的相关文章。那么小编在网络上汇集了一些有关“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 and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

exec()

1、exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。

>>> eval('a=1+2') #执行语句报错Traceback (most recent call last): File "<pyshell#107>", line 1, in <module> eval('a=1+2') #执行语句报错 File "<string>", line 1 a=1+2 ^SyntaxError: invalid syntax>>> exec('a=1+2') #执行语句>>> a3

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 = 9num3 = num + num2''', g, l)>>> l['num2'] #l中num2值已经改变9

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#127>", 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(){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'code1': 'for i in range(0, 10):print (i)', 'compile1': <code object <module> at 0x0000000002F11420, file "", line 1>, 'i': 9, 'code2': '1 + 2 + 3 + 4', 'compile2': <code object <module> at 0x0000000002F4BED0, file "", line 1>, 'code3': 'name = input("please input your name:")', 'compile3': <code object <module> at 0x0000000002F2F390, file "", line 1>, 'name': "'python3.6.1'", 'A': <class '__main__.A'>, 'a': 3, 'B': <class '__main__.B'>, 'math': <module 'math' (built-in)>, 'b': <__main__.B object at 0x0000000002FD7B38>, 'seasons': ['Spring', 'Summer', 'Fall', 'Winter'], 'g': {'__builtins__': {}}, 'l': {'num2': 9, 'num3': 11}, 'num': 1, 'num2': 2}>>> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败Traceback (most recent call last): File "<pyshell#131>", line 1, in <module> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败 File "<string>", line 1, in <module>NameError: name 'num' is not defined>>> l = locals()>>> l{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'code1': 'for i in range(0, 10):print (i)', 'compile1': <code object <module> at 0x0000000002F11420, file "", line 1>, 'i': 9, 'code2': '1 + 2 + 3 + 4', 'compile2': <code object <module> at 0x0000000002F4BED0, file "", line 1>, 'code3': 'name = input("please input your name:")', 'compile3': <code object <module> at 0x0000000002F2F390, file "", line 1>, 'name': "'python3.6.1'", 'A': <class '__main__.A'>, 'a': 3, 'B': <class '__main__.B'>, 'math': <module 'math' (built-in)>, 'b': <__main__.B object at 0x0000000002FD7B38>, 'seasons': ['Spring', 'Summer', 'Fall', 'Winter'], 'g': {'__builtins__': {}}, 'l': {...}, 'num': 1, 'num2': 2}>>> exec('num3 = num + 1',{},l)#指定了globals参数,globals中无num变量,指定了locals变量,locals变量含有num变量 执行成功>>> l{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'code1': 'for i in range(0, 10):print (i)', 'compile1': <code object <module> at 0x0000000002F11420, file "", line 1>, 'i': 9, 'code2': '1 + 2 + 3 + 4', 'compile2': <code object <module> at 0x0000000002F4BED0, file "", line 1>, 'code3': 'name = input("please input your name:")', 'compile3': <code object <module> at 0x0000000002F2F390, file "", line 1>, 'name': "'python3.6.1'", 'A': <class '__main__.A'>, 'a': 3, 'B': <class '__main__.B'>, 'math': <module 'math' (built-in)>, 'b': <__main__.B object at 0x0000000002FD7B38>, 'seasons': ['Spring', 'Summer', 'Fall', 'Winter'], 'g': {'__builtins__': {}}, 'l': {...}, 'num': 1, 'num2': 2, 'num3': 2}

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。

欢迎关注公众号,访问更多精彩:数据之魅。

标签: #exec函数 #exec函数的作用