这个内置函数有助于执行动态创建的程序。exec() 函数接收一个字符串或代码块进行执行。它被解析并作为 Python 语句执行。
exec(object, globals, locals) #Where object can be a string or a code object
安全风险
如果使用 Unix 系统(macOS、Linux 等)并导入 OS 模块,它有助于提供文件读写等操作系统功能。如果用户使用 exec(input()) 输入一个值,它可能会发出命令来更改文件甚至使用命令 os.system('rm -rf *') 删除所有文件。
接受 3 个参数,其中第一个参数是对象,如果对象是字符串,则作为 Python 语句执行;如果是一个打开的文件,则执行直到文件结束;如果是一个代码对象,则直接执行。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 对象 | 可以是字符串或代码对象 | 必需 |
| globals | 包含全局变量的字典。 | 可选 |
| locals | 包含局部变量的字典。 | 可选 |
它不返回任何值。它只执行给定的字符串或代码对象。
x = 1
exec('print(x==1)')
exec('print(x+2)')
输出
True 3
from math import *
for l in range(1, 3):
func = input("Enter Code Snippet to execute:\n")
try:
exec(func)
except Exception as ex:
print(ex)
break
print('Done')
输出
Enter Code Snippet to execute: print(sqrt(16)) 4.0 Enter Code Snippet to execute: print(min(2,1)) 1 Done
from math import *
exec('print(dir())', {})
# This code will raise an exception
# exec('print(sqrt(9))', {})
输出
['__builtins__']
from math import *
globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)
输出
['dir', 'print']