约 1441 字

约 7 分钟

#Python 的内置函数 exec

说明:执行代码。

#函数说明

def exec(source:str|codeobject, /, globals:dict=None, locals:mapping=None, *, closure=None):
    '''
    执行代码

    :param source: Python 代码
    :param globals : 全局命名空间
    :param locals : 局部命名空间
    :param closure : 闭包
    '''

说明

执行代码。

参数

  • source - 字符串形式的 Python 代码,或者是代码对象
  • globals - 全局命名空间字典
    • 默认为 None,即使用当前环境的全局命名空间
    • 如果不包含 __builtins__ 键,则自动插入内置模块 builtins 的引用作为 __builtins__ 键的值
  • locals - 局部命名空间字典
    • 默认为 None,即使用 globals 作为 locals
    • 如果 globals 也为 None 则使用当前环境的局部命名空间
  • closure - 闭包,仅在 source 参数是一个包含自由变量的代码对象时可用

返回值

无。

#示例

# 执行单行代码
exec("print('hello world')")

# 使用当前命名空间
x = 233
exec("print(x + 1)")

# 使用 globals 参数传入命名空间
exec("print(x + 1)", globals={'x': 666})

# 执行代码块
code:str = '''
def greet(name:str):
    print('hello', name)

greet(name)
'''
exec(code, globals={'name': 'Alice'})

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#注意事项

  • exec 可以执行任意代码,存在严重的安全风险,永远不要直接执行不可信来源的输入
  • exec 的执行速度比直接执行代码慢,频繁地调用会显著影响性能
  • 在需要限制执行环境时,应该提供 globals 和 locals 字典
  • 解析数据时,更安全的替代方案包括 ast.literal_eval() 或 JSON

#推荐阅读

更新: 2025/10/25

作者: PlanC

创建: 2025/6/9