专业编程基础技术教程

网站首页 > 基础教程 正文

Python3.6内置函数(12)——compile()

ccvgpt 2024-10-12 13:44:56 基础教程 6 ℃

英文文档

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

Python3.6内置函数(12)——compile()

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 (‘<string>’ 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).

compile()

1、将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

2、参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。

3、参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。

4、参数mode:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,mode应指定为‘exec’;当source中只包含一个简单的求值表达式,mode应指定为‘eval’;当source中包含了交互式命令语句,mode应指定为’single’。

>>> #流程语句使用exec

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。

欢迎关注公号,访问更多精彩:AiryData

如需转载,请联系授权,谢谢合作。

Tags:

最近发表
标签列表