Python compile() 函式



**Python compile() 函式** 用於將原始碼編譯成 Python 程式碼物件。此處,Python 程式碼物件表示一段可執行且不可變的位元組碼。

有兩個名為exec()eval() 的方法與 compile() 函式一起使用來執行編譯後的程式碼。

compile() 函式是 內建函式 之一,不需要匯入任何模組。

語法

Python **compile()** 函式的語法如下所示:

compile(source, fileName, mode, flag, dont_inherit, optimize)

引數

Python **compile()** 函式接受以下引數:

  • **source** - 此引數表示字串或 AST 物件。

  • **fileName** - 它指定載入原始碼的檔名。如果原始碼不是從檔案載入的,請指定任意名稱。

  • **mode** - 它指示要編譯的程式碼型別。如果 source 包含一系列語句,則可以為 "exec"。如果它包含單個表示式,則 mode 可以為 "eval",或者如果 source 包含單個互動式語句,則可以為 "single"。

  • **flag** - 它指定哪些未來語句會影響原始碼的編譯。其預設值為 0。

  • **dont_inherit** - 此引數的預設值為 False。它指定如何編譯原始碼。

  • **optimize** - 它表示編譯器的最佳化級別。

返回值

Python **compile()** 函式返回一個 Python 程式碼物件。

compile() 函式示例

練習以下示例以瞭解 Python 中 **compile()** 函式的使用。

示例:compile() 函式的使用

要執行單個表示式,我們使用 eval 模式。以下示例展示了 Python compile() 函式在 eval 模式下編譯單個表示式的用法。

operation = "5 * 5"
compiledExp = compile(operation, '<string>', 'eval')
output = eval(compiledExp)
print("The result after compilation:", output) 

執行以上程式時,會產生以下結果:

The result after compilation: 25

示例:使用 compile() 執行兩個表示式

如果原始碼是一系列語句,我們使用 exec 模式執行。在下面的程式碼中,我們有一個包含兩個語句的表示式,並且我們使用 compile() 函式來編譯這些語句。

exprsn = "kOne = 'vOne'"
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)
print("The value of key after compilation:", kOne)

以下是以上程式碼的輸出:

The value of key after compilation: vOne

示例:使用 compile() 執行多個表示式

下面的程式碼展示瞭如何使用 compile() 函式編譯多個語句。由於原始碼包含多個表示式,因此我們需要使用 exec 模式。

exprsn = """
def msg(name):
   print('Tutorials' + name)

msg('Point')
"""
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)  

以上程式碼的輸出如下所示:

TutorialsPoint
python_built_in_functions.htm
廣告