Python compile() 函數
描述
compile() 函數將一個字串編譯為位元組代碼。
語法
以下是 compile() 方法的語法:
compile(source, filename, mode[, flags[, dont_inherit]])
參數
- source -- 字串或者AST(Abstract Syntax Trees)對象。。
- filename -- 代碼檔案名稱,如果不是從檔讀取代碼則傳遞一些可辨認的值。
- mode -- 指定編譯代碼的種類。可以指定為 exec, eval, single。
- flags -- 變數作用域,局部命名空間,如果被提供,可以是任何映射對象。。
- flags和dont_inherit是用來控制編譯源碼時的標誌
返回值
返回運算式執行結果。
實例
以下展示了使用 compile 函數的實例:
>>>str = "for i in range(0,10): print(i)"
>>> c = compile(str,'','exec') # 編譯為位元組代碼對象
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17