Python函数-compile()

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

作用:

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

      参数source:字符串或者AST(Abstract Syntax Trees)对象。

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

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

      参数flag和dont_inherit:这两个参数暂不介绍,可选参数。

实例:

 1 >>> code = "for i in range(0, 10): print i"
 2 >>> cmpcode = compile(code, '', 'exec')
 3 >>> exec cmpcode
 4 0
 5 1
 6 2
 7 3
 8 4
 9 5
10 6
11 7
12 8
13 9
14 >>> str = "3 * 4 + 5"
15 >>> a = compile(str,'','eval')
16 >>> eval(a)
17 17
原文地址:https://www.cnblogs.com/guyuyuan/p/6889248.html