Python 直譯器及其模式



Python 直譯器

Python 是一種基於直譯器的語言。在 Linux 系統中,Python 的可執行檔案安裝在 /usr/bin/ 目錄下。對於 Windows,可執行檔案 (python.exe) 位於安裝資料夾中(例如 C:\python311)。

本教程將教你Python 直譯器如何在互動模式和指令碼模式下工作。Python 程式碼一次執行一條語句。Python 直譯器有兩個元件。翻譯器檢查語句的語法。如果正確,它會生成中間位元組碼。然後有一個 Python 虛擬機器將位元組碼轉換為原生二進位制程式碼並執行它。下圖說明了該機制。

Python Interpreter

Python 直譯器具有互動模式和指令碼模式。

Python 直譯器 - 互動模式

從命令列終端啟動 Python 時,如果沒有附加任何選項,則會出現 Python 提示符 >>>,並且 Python 直譯器的工作原理是REPL(讀取、評估、列印、迴圈)。在 Python 提示符前面輸入的每個命令都會被讀取、翻譯和執行。一個典型的互動式會話如下所示。

>>> price = 100
>>> qty = 5
>>> total = price*qty
>>> total
500
>>> print ("Total = ", total)
Total = 500

要關閉互動式會話,請輸入行尾字元(Linux 為 ctrl+D,Windows 為 ctrl+Z)。您也可以在 Python 提示符前面鍵入quit() 並按 Enter 鍵返回到作業系統提示符。

>>> quit()

$

標準 Python 發行版提供的互動式 shell 不具備行編輯、歷史搜尋、自動完成等功能。您可以使用其他高階互動式直譯器軟體,例如IPythonbpython,以獲得更多功能。

Python 直譯器 - 指令碼模式

與在互動式環境中一次輸入並獲取一條指令的結果不同,可以將一組指令儲存在文字檔案中,確保其具有.py副檔名,並將檔名用作 Python 命令的命令列引數。

使用任何文字編輯器(例如 Linux 上的 vim 或 Windows 上的記事本)將以下幾行儲存為prog.py

print ("My first program")
price = 100
qty = 5
total = price*qty
print ("Total = ", total)

當我們在Windows機器上執行上述程式時,將產生以下結果

C:\Users\Acer>python prog.py
My first program
Total = 500

請注意,儘管Python一次性執行整個指令碼,但在內部它仍然是逐行執行的。

對於Java之類的基於編譯器的語言,只有在整個程式碼沒有錯誤的情況下,原始碼才會轉換為位元組碼。而在Python中,語句會一直執行到遇到第一個錯誤。

讓我們在上述程式碼中故意引入一個錯誤。

print ("My first program")
price = 100
qty = 5
total = prive*qty #Error in this statement
print ("Total = ", total)

請注意變數名prive拼寫錯誤,應為price。嘗試像以前一樣再次執行指令碼:

C:\Users\Acer>python prog.py
My first program
Traceback (most recent call last):
  File "C:\Python311\prog.py", line 4, in <module>
   total = prive*qty
   ^^^^^
NameError: name 'prive' is not defined. Did you mean: 'price'?

請注意,錯誤語句之前的語句已執行,然後出現錯誤訊息。因此,現在可以清楚地看到Python指令碼是以解釋方式執行的。

Python直譯器 - 使用Shebang #!

除了像上面那樣執行Python指令碼外,該指令碼本身也可以像shell指令碼一樣在Linux中自執行。您必須在指令碼頂部新增一行shebang。Shebang指示哪個可執行檔案用於解釋指令碼中的Python語句。指令碼的第一行以#!開頭,後跟Python可執行檔案的路徑。

修改prog.py指令碼如下:

#! /usr/bin/python3.11

print ("My first program")
price = 100
qty = 5
total = price*qty
print ("Total = ", total)

要將指令碼標記為自執行,請使用chmod命令

$ chmod +x prog.py

現在,您可以直接執行指令碼,而無需將其用作命令列引數。

$ ./hello.py

互動式Python - IPython

IPython(代表Interactive Python)是Python的一個增強型且功能強大的互動式環境,與標準Python shell相比具有許多功能。IPython最初由Fernando Perez於2001年開發。

IPython具有以下重要特性:

  • IPython 的物件自省能力,可以在執行時檢查物件的屬性。

  • 其語法高亮顯示功能有助於識別語言元素,例如關鍵字、變數等。

  • 互動歷史會被內部儲存並可以重現。

  • 關鍵字、變數和函式名的Tab自動補全是最重要的特性之一。

  • IPython的魔法命令系統可用於控制Python環境和執行作業系統任務。

  • 它是Jupyter Notebook和其他Jupyter專案前端工具的主要核心。

使用PIP安裝程式實用程式安裝IPython。

pip3 install ipython

從命令列啟動IPython

C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:

與標準直譯器中的常規>>>提示符不同,您會注意到兩個主要的IPython提示符,如下所述:

  • In[1]出現在任何輸入表示式之前。

  • Out[1]出現在輸出之前。

In [1]: price = 100
In [2]: quantity = 5
In [3]: total = price*quantity
In [4]: total
Out[4]: 500
In [5]:

Tab自動補全是由IPython提供的最有用的增強功能之一。當您在物件前面的點後按下Tab鍵時,IPython會彈出相應的函式列表。

IPython透過在物件前面新增?來提供任何物件的資訊(自省)。它包括文件字串、函式定義和類的建構函式詳細資訊。例如,要探索上面定義的字串物件var,請在輸入提示符中輸入var?

In [5]: var = "Hello World"
In [6]: var?
Type: str
String form: Hello World
Length: 11
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

IPython的魔法函式非常強大。行魔法允許您在IPython內部執行DOS命令。讓我們在IPython控制檯中執行dir命令

In [8]: !dir *.exe
 Volume in drive F has no label.
 Volume Serial Number is E20D-C4B9

 Directory of F:\Python311

07-02-2023 16:55            103,192 python.exe
07-02-2023 16:55            101,656 pythonw.exe
                2 File(s)    204,848 bytes
                0 Dir(s)  105,260,306,432 bytes free

Jupyter Notebook是一個基於Web的介面,用於Python、Julia、R和許多其他程式設計環境。對於Python,它使用IPython作為其主要核心。

廣告