Python 内建函数 - compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

本文介绍了Python内置的compile函数,用于将源代码编译成代码或AST对象。它支持'exec'、'eval'和'single'三种模式,分别对应编译语句序列、表达式和交互式语句。此外,文章还提到了编译时的未来语句控制、优化级别选项以及对null字节的处理。compile函数常用于在线代码编辑、用户自定义代码等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file (‘’ is commonly used).

The mode argument specifies what kind of code must be compiled; it can be ‘exec’ if source consists of a sequence of statements, ‘eval’ if it consists of a single expression, or ‘single’ if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

The optional arguments flags and dont_inherit control which future statements (see PEP 236) 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(). If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the future module.

The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; debug is true), 1 (asserts are removed, debug is false) or 2 (docstrings are removed too).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

If you want to parse Python code into its AST representation, see ast.parse().

Note When compiling a string with multi-line code in ‘single’ or ‘eval’ mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in ‘exec’ mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, TypeError was raised when null bytes were encountered in source.

直译

source编译为代码或AST对象,代码对象可以被exec()eval()执行。

  • source既可是普通字符串、字节字符串,也可是AST对象。关于如何操作AST对象详情参考ast模块。
  • filename参数应当给定读入代码的文件,如果不能从文件读取则传入一些可识别的值(常用’’)
  • mode参数指定编译代码的类型。如果source包含语句序列,它可以是’exec’;如果source单独表达式,它可以是’eval’;如果source包含单独的交互式语句(除None外,等于某值的表达式语句将会被打印出来),它可以是’single’。
  • 可选参数flagsdont_inherit控制那些影响source编译的future statements(见PEP 236)。如果两者不存在(或都为0),代码将用那些future statements编译,这些future statements事实上在那些调用compile()的代码中。如果给定flagsdont_inherit为空,除了那些可能使用的future statements,由flags参数指定的future statements也将被使用。如果dont_inherit为非零整数,那么flags参数则是 — 用于编译而调用的future statements将会被忽略。
    Future statements(未来语句?)是由位(那些可以按位或运算来指定多个语句)指定的,位域需要指定一个既定特征,该特征可以被发现作为__future__模块中_Feature实例上的compiler_flag属性。
  • optimize参数指定编译器的优化级别,默认值-1选择的解释器的优化级别为-O选项。具体级别有:0(无优化,__debug__为true),1(移除断言,__debug__为false)或2(移除文档字符串)。

如果编译资源无效则引发SyntaxError,若资源包含null字节则是ValueError。
如果你想将Python代码解析为它的AST形式,详见ast.parse().
注意在’single’或’eval’模式下用多行代码解析字符串时,输入的至少由一个换行符结尾,这是为了方便在代码模块中检测不完整和完整的语句。

version 3.2变动: 允许使用Windows和Mac换行符,’exec’模式下的输入也不再必须使用换行符结尾。增加optimize参数。
version 3.5变动: 以前,当资源中遇到null字节时引发TypeError。

实例

三种mode

# 'exec'模式
>>> source = "print('Hello world!')"
>>> c_source = compile(source, '', 'exec')
>>> exec(c_source)
Hello world!

# 'eval'模式
>>> ex = '12 % 5'
>>> c_ex = compile(ex, '', 'eval')
>>> eval(c_ex)
2

# 'single'模式
>>> x = "i = input('Number you want to show: ')"
>>> c_x = compile(x, '', 'single')
>>> exec(c_x)
Number you want to show: 10
>>> eval(c_x)
Number you want to show: 10

多行

# 'exec'模式多行
>>> x = "i = input('Number you want to show: ')\nprint(i)"
>>> c_x = compile(x, '', 'exec')
>>> exec(c_x)
Number you want to show: 12
12

# 'single'模式多行
>>> x = "i = input('Number you want to show: ')\nprint(i)"
>>> c_x = compile(x, '', 'single')
Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    c_x = compile(x, '', 'single')
  File "<string>", line 1
    i = input('Number you want to show: ')
                                         ^
SyntaxError: multiple statements found while compiling a single statement

Note

关于使用问题,一开始我也不太明白,为什么非要将字符串可编译化,经过stackoverflow和google的一些资料查询,目前可能考虑到的用处主要有:

  • 在线代码编辑和实时交互
  • 用户自定义代码

拓展阅读

exec()
eval()
ast

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值