16. 附錄¶
16.1. 互動模式¶
16.1.1. 錯誤處理¶
When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an except
clause in a try
statement
are not errors in this context.) Some errors are unconditionally fatal and
cause an exit with a nonzero exit status; this applies to internal inconsistencies and
some cases of running out of memory. All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.
向主提示字元或次提示字元輸入中斷字元(通常是 Control-C 或 Delete )會取消輸入並返回到主提示字元。 [1] 在指令執行過程中輸入一個中斷,會引發 KeyboardInterrupt
例外,但可以通過 try
陳述式來處理。
16.1.2. 可執行的 Python 腳本¶
在類 BSD 的 Unix 系統上,Python 腳本可以直接執行,就像 shell 腳本一樣,通過放置以下這行:
#!/usr/bin/env python3.5
(假設直譯器在用戶的 PATH
上)在腳本的開頭並給檔案一個可執行模式。 #!
必須是檔案的前兩個字元。 在某些平台上,第一行必須以 Unix 樣式的換行 ('\n'
) 結尾,而不是 Windows ('\r\n'
) 換行。 請注意,井號 '#'
用於在 Python 中開始註解。
可以使用 chmod 指令為腳本賦予可執行模式或權限。
$ chmod +x myscript.py
在 Windows 系統上,沒有「可執行模式」的概念。 Python 安裝程式會自動將 .py
檔案與 python.exe
聯繫起來,這樣雙擊 Python 檔案就會作為腳本運行。副檔名也可以是 .pyw
,在這種情況下,通常會出現的控制台視窗會被隱藏。
16.1.3. 互動式啟動檔案¶
當你互動式地使用 Python 時,每次啟動直譯器時執行一些標準指令是非常方便的。你可以通過設置一個名為 PYTHONSTARTUP
的環境變數來實現,該變數是一個包含啟動指令的檔案名。它的功能類似 Unix shell 的 .profile
。
這個檔案只在互動模式中被讀取,當 Python 從腳本中讀取指令時,此檔案不會被讀取,當 /dev/tty
作為指令的明確來源時也不會(否則表現得像互動模式)。它在執行互動式指令的同一命名空間中執行,因此它所定義或 import 的物件可以在互動模式中不加限定地使用。你也可以在這個檔案中改變 sys.ps1
和 sys.ps2
等提示字元。
如果你想從當前目錄中讀取一個額外的啟動檔案,你可以在全域啟動檔案中使用類似 if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read()
的程式碼設定這個行為。如果你想在一個腳本中使用啟動檔案,你必須在腳本中明確地這樣做:
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
with open(filename) as fobj:
startup_file = fobj.read()
exec(startup_file)
16.1.4. 客製化模組¶
Python provides two hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code:
>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.5/site-packages'
現在,您可以在該目錄中創建一個名為 usercustomize.py
的檔案,並將您想要的任何內容放入其中。它會影響 Python 的每次呼叫,除非它以 -s
選項啟動以禁用自動 import 。
sitecustomize works in the same way, but is typically created by an
administrator of the computer in the global site-packages directory, and is
imported before usercustomize. See the documentation of the site
module for more details.
註解