Python compile() 函数用于将源代码编译成 Python 代码对象。在这里,Python 代码对象表示一段可执行且不可变的字节码。
有两个名为 exec() 和 eval() 的方法与 compile() 函数一起使用来执行编译的代码。
compile() 函数是内置函数之一,不需要任何模块导入。
语法
Python compile() 函数的语法如下 -
compile(source, fileName, mode, flag, dont_inherit, optimize)
参数
Python compile() 函数接受以下参数 -
- source − 此参数表示字符串或 AST 对象。
- fileName - 它指定将从中加载源的文件的名称。如果未从文件加载源,请指定您选择的任何名称。
- mode − 它表示要编译的代码类型。如果 source 由一系列语句组成,则可以为 “exec”。如果它由单个表达式组成,则 source 由单个交互式语句组成,则模式可以是 “eval” 或 “single”。
- flag − 它指定哪些 future 语句会影响源的编译。其默认值为 0。
- dont_inherit − 此参数的默认值为 False。它指定如何编译源。
- optimize - 它表示编译器的优化级别。
返回值
Python compile() 函数返回 Python 代码对象。
compile() 函数示例
练习以下示例来理解 Python 中 compile() 函数的用法:
示例:使用 compile() 函数
要执行单个表达式,我们使用 eval 模式。以下示例显示了在 eval 模式下编译单个表达式时使用 Python compile() 函数。
operation = "5 * 5"
compiledExp = compile(operation, '<string>', 'eval')
output = eval(compiledExp)
print("The result after compilation:", output)
当我们运行上述程序时,它会产生以下结果——
The result after compilation: 25
示例:使用 compile() 执行两个表达式
如果源是语句序列,我们使用 exec 模式执行。在下面的代码中,我们有一个包含两个语句的表达式,我们使用 compile() 函数来编译这些语句。
exprsn = "kOne = 'vOne'"
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)
print("The value of key after compilation:", kOne)
以下是上述代码的输出 -
The value of key after compilation: vOne
示例:使用 compile() 执行多个表达式
下面的代码显示了如何使用 compile() 函数编译多个语句。由于源包含多个表达式,因此我们需要使用 exec 模式。
exprsn = """
def msg(name):
print('qikepu' + name)
msg('Com')
"""
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)
上述代码的输出如下 -
qikepuCom