python预编译(compile)

前面学习了一下python执行字符串中的表达式和语句的方法。但是当我们要多次执行某段代码时,python会一遍一遍的先编译再执行,这样就降低了效率。
这时我们可以先将此部分的代码编译完,后面直接调用就好了。
例如前面的例子,就可以改为:

compile(source, filename, mode[, flags[, dont_inherit]])
Compile the source into a code or AST object. Code objects can be executed by an exec statement or evaluated by a call to eval(). source can either be a 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).

作者: Leniy

Do not , for one repulse , give up the purpose that you resolved to effect . 本文著作版权归Leniy所有,并受法律保护。 转载、使用整体或任何部分的内容(包含但不限于各个页面的标题、评论框提示语)须经过Leniy的授权。 CopyRight © 2006-2017 Leniy.org all rights reserved.

6 thoughts on “python预编译(compile)

发表评论

电子邮件地址不会被公开。 必填项已用*标注