Python compile()函数
Python compile()函数将源代码作为输入并返回一个代码对象,该代码对象可以执行,以后可以由 exec()函数执行。
Syntax compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Parameters:
- Source – It can be a normal string, a byte string, or an AST object
- Filename -This is the file from which the code was read. If it wasn’t read from a file, you can give a name yourself.
- Mode – Mode can be exec, eval or single.
- a. eval – If the source is a single expression.
- b. exec – It can take a block of a code that has Python statements, class and functions and so on.
- c. single – It is used if consists of a single interactive statement
- Flags (optional) and dont_inherit (optional) – Default value=0. It takes care that which future statements affect the compilation of the source.
- Optimize (optional) – It tells optimization level of compiler. Default value -1.
Python compile()函数示例
示例 1: Python中的简单 compile() 示例。
这里文件名是 mulstring 和 exec 模式允许使用 exec() 方法和 compile 方法将字符串转换为Python代码对象。
Python3
# Python code to demonstrate working of compile().
# Creating sample sourcecode to multiply two variables
# x and y.
srcCode = 'x = 10\ny = 20\nmul = x * y\nprint("mul =", mul)'
# Converting above source code to an executable
execCode = compile(srcCode, 'mulstring', 'exec')
# Running the executable code.
exec(execCode)
Python
# Another Python code to demonstrate working of compile().
x = 50
# Note eval is used for single statement
a = compile('x', 'test', 'single')
print(type(a))
exec(a)
Python3
String = "Welcome to Geeksforgeeks"
print(String)
Python3
# reading code from a file
f = open('main.py', 'r')
temp = f.read()
f.close()
code = compile(temp, 'main.py', 'exec')
exec(code)
Python3
# Another Python code to demonstrate
# working of compile() with eval.
x = 50
# Note eval is used for statement
a = compile('x == 50', '', 'eval')
print(eval(a))
输出:
mul = 200
示例 2:编译的另一个演示工作
Python
# Another Python code to demonstrate working of compile().
x = 50
# Note eval is used for single statement
a = compile('x', 'test', 'single')
print(type(a))
exec(a)
输出:
50
示例 3: Python从文件编译函数
在本例中,我们将获取带有一些字符串显示方法的 main.py 文件,然后我们读取文件内容并对其进行编译以对对象进行编码并执行它。
主要.py:
Python3
String = "Welcome to Geeksforgeeks"
print(String)
代码:这里我们将文件内容作为字符串读取,然后编译成代码对象。
Python3
# reading code from a file
f = open('main.py', 'r')
temp = f.read()
f.close()
code = compile(temp, 'main.py', 'exec')
exec(code)
输出:
Welcome to Geeksforgeeks
示例 4:Compile() 与 eval()
当源是单个表达式时,这里使用 eval。
Python3
# Another Python code to demonstrate
# working of compile() with eval.
x = 50
# Note eval is used for statement
a = compile('x == 50', '', 'eval')
print(eval(a))
输出:
True
应用:
- 如果Python代码是字符串形式或者是一个 AST 对象,并且您想将其更改为代码对象,那么您可以使用 compile() 方法。
- compile() 方法返回的代码对象稍后可以使用以下方法调用:exec() 和 eval(),它们将执行动态生成的Python代码。