Python compile()函数

Python compile() function is used to compile the source into code object or AST module object. The returned code object can be executed using exec() or eval() function based on the provided mode to construct the code object.

Python compile()函数用于将源代码编译为代码对象或AST模块对象。 可以根据提供的模式使用exec()eval()函数执行返回的代码对象,以构造代码对象。

Python compile() (Python compile())

Python compile() function syntax is:

Python compile()函数语法为:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Let’s look at the compile() function arguments.

让我们看一下compile()函数参数。

  • source: Source to create the code object. This can be string, byte string or AST module object.

    source :创建代码对象的源。 这可以是字符串,字节字符串或AST模块对象。
  • filename: If you are reading code string from a file, you should provide its name here for reference. It’s not used in creating the code object, rather it’s used for making code readable.

    filename :如果您正在从文件中读取代码字符串,则应在此处提供其名称以供参考。 它不是用于创建代码对象,而是用于使代码可读。
  • mode: This argument specifies the type of code. Allowed values are exec, eval and single. Use exec if source contains multiple python statements. Use eval if source is a single python expression. Use single if source consists of a single interactive statement.

    mode :此参数指定代码的类型。 允许的值为execevalsingle 。 如果源包含多个python语句,请使用exec。 如果source是单个python表达式,请使用eval。 如果源由单个交互式语句组成,则使用单个。
  • The optional arguments flags and dont_inherit control which future statements affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile().

    可选参数flagsdont_inherit控制将来的哪些语句会影响源代码的编译。 如果两个都不存在(或两个都不为零),则使用在调用compile()的代码中有效的将来的语句来编译代码。
  • The argument optimize specifies the optimization level of the compiler.

    参数optimize指定编译器的优化级别。

Python compile()示例 (Python compile() examples)

Let’s look at compile() function example with different sources.

让我们看一下具有不同来源的compile()函数示例。

将字符串源编译为代码 (Compiling String Source to Code)

# compile() with string source
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)

Output:

输出:

<class 'code'>
sum = 15

Notice that the compile function return type is ‘code’ object. Also, we are using exec() here because source string contains multiple python statements. Notice that code object is being executed by the exec() function and “sum = 15” is getting printed in the console.

请注意,编译函数的返回类型为“代码”对象。 另外,我们在这里使用exec(),因为源字符串包含多个python语句。 请注意,代码对象正在由exec()函数执行,并且“ sum = 15”正在控制台中打印。

从文件读取代码并进行编译 (Reading Code from a File and Compiling)

Let’s say we have my_code.py file with following content.

假设我们有my_code.py文件,其中包含以下内容。

x = 10
y = 20
print('Multiplication = ', x * y)

We can read this file content as a string and compile it to code object and execute it.

我们可以将此文件内容作为字符串读取,并将其编译为代码对象并执行。

# reading code from a file
f = open('my_code.py', 'r')
code_str = f.read()
f.close()
code = compile(code_str, 'my_code.py', 'exec')
exec(code)

Output: Multiplication = 200

输出: Multiplication = 200

用eval()编译() (compile() with eval())

Let’s see an example to compile python expression to code and execute it using eval() function.

让我们看一个示例,将python表达式编译为代码并使用eval()函数执行它。

# eval example
x = 5
code = compile('x == 5', '', 'eval')
result = eval(code)
print(result)

code = compile('x + 5', '', 'eval')
result = eval(code)
print(result)

Output:

输出:

True
10

带字节字符串源的compile() (compile() with byte string source)

Let’s look at an example of using byte string as source.

让我们看一个使用字节字符串作为源的示例。

bytes_str = bytes('x == 5', 'utf-8')
print(type(bytes_str))
code = compile(bytes_str, '', 'eval')
result = eval(code)
print(result)

Output:

输出:

<class 'bytes'>
True

使用AST对象进行compile() (compile() with AST Object)

Let’s look at an example of using AST object with compile() function.

我们来看一个使用AST对象和compile()函数的示例。

import ast

ast_object = ast.parse("print('Hello world!')")
print(type(ast_object))
code = compile(ast_object, filename="", mode="exec")
print(type(code))
exec(code)

Output:

输出:

<class '_ast.Module'>
<class 'code'glt;
Hello world!

摘要 (Summary)

Python compile() function allows us to create code object from a string, which can be later executed using exec() and eval() functions. You should take extra care if you are taking user input and compile it to code and execute it because it can have unwanted effects, for example issuing rm -rf / command.

Python compile()函数允许我们从字符串创建代码对象,以后可以使用exec()和eval()函数执行该对象。 如果要接受用户输入并将其编译为代码并执行,则应格外小心,因为它可能产生不良影响,例如发出rm -rf / command。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22772/python-compile-function

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值