compile(source, filename, mode[, flags[, dont_inherit]])


参数source:字符串或者ast(abstract syntax trees)对象。

参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。

参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。




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 (” 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.

this function raises syntaxerror if the compiled source is invalid, and typeerror if the source contains null bytes.

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 2.3: the flags and dont_inherit arguments were added.

changed in version 2.6: support for compiling ast objects.

changed in version 2.7: allowed use of windows and mac newlines. also input in ‘exec’ mode does not have to end in a newline anymore.


>>> code = “for i in range(0, 10): print i”
>>> cmpcode = compile(code, ”, ‘exec’)
>>> exec cmpcode
>>> str = “3 * 4 + 5″
>>> a = compile(str,”,’eval’)
>>> eval(a)

Posted in 未分类