The Python interpreter is usually installed as /usr/local/bin/python on those machines where it is available; putting /usr/local/bin in your Unix shell's search path makes it possible to start it by typing the command
通常 Python 的解釋器被安裝在目標(biāo)機(jī)器的 /usr/local/bin/python 目錄下;把 /usr/local/bin 目錄放進(jìn)你的Unix Shell 的搜索路徑里,確保它可以通過輸入
python
to the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
來啟動(dòng)。因?yàn)榘惭b路徑是可選的,所以也有可能安裝在其它位置,你可以與安裝 Python 的用戶或系統(tǒng)管理員聯(lián)系。(例如,/usr/local/python就是一個(gè)很常見的選擇)
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn't work, you can exit the interpreter by typing the following commands: "import sys; sys.exit()".
輸入一個(gè)文件結(jié)束符(Unix 上是Ctrl+D,Windows上是Ctrl+Z)解釋器會(huì)以0值退出(就是說,沒有什么錯(cuò)誤,正常退出--譯者)。如果這沒有起作用,你可以輸入以下命令退出:"import sys; sys.exit()"。
The interpreter's line-editing features usually aren't very
sophisticated. On Unix, whoever installed the interpreter may
have enabled support for the GNU readline library, which adds more
elaborate interactive editing and history features. Perhaps the
quickest check to see whether command line editing is supported is
typing Control-P to the first Python prompt you get. If it beeps,
you have command line editing; see Appendix P
is echoed, command line editing isn't available; you'll
only be able to use backspace to remove characters from the
current line.
解釋器的行編輯功能并不很復(fù)雜。裝在Unix上的解釋器可能會(huì)有GNU
readline
庫支持,這樣就可以額外得到精巧的交互編輯和歷史記錄功能?赡軝z查命令行編輯器支持能力最方便的方式是在主提示符下輸入Ctrl-P。如果有嘟嘟聲(計(jì)算機(jī)揚(yáng)聲器),說明你可以使用命令行編輯功能,從附錄
A P
顯示了出來,說明命令行編輯功能不可用,你只有用退格鍵刪掉輸入的命令了。
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
解釋器的操作有些像 Unix Shell:使用終端設(shè)備做為標(biāo)準(zhǔn)輸入來調(diào)用它時(shí),解釋器交互的解讀和執(zhí)行命令,通過文件名參數(shù)或以文件做為標(biāo)準(zhǔn)輸入設(shè)備時(shí),它從文件中解讀并執(zhí)行腳本。
A second way of starting the interpreter is "python -c command [arg] ...", which executes the statement(s) in command, analogous to the shell's -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is best to quote command in its entirety with double quotes.
啟動(dòng)解釋器的第二個(gè)方法是"python -c command [arg] ...",這種方法可以在命令行中直接執(zhí)行語句,等同于Shell的 -c選項(xiàng)。因?yàn)镻ython語句通常會(huì)包括空格之類的特殊字符,所以最好把整個(gè)語句用雙引號(hào)包起來。
Note that there is a difference between "python file" and "python <file". In the latter case, input requests from the program, such as calls to input() and raw_input(), are satisfied from file. Since this file has already been read until the end by the parser before the program starts executing, the program will encounter end-of-file immediately. In the former case (which is usually what you want) they are satisfied from whatever file or device is connected to standard input of the Python interpreter.
注意"python file"和"python <file"是有區(qū)別的。對(duì)于后一種情況,程序中類似于調(diào)用 input()raw_input() 這樣的輸入請(qǐng)求,來自于確定的文件。因?yàn)樵诮馕銎鏖_始執(zhí)行之前,文件已經(jīng)完全讀入,所以程序指向文件尾。在前一種情況(這通常是你需要的)它們從來自于任何聯(lián)接到 Python 解釋器的標(biāo)準(zhǔn)輸入,無論它們是文件還是其它設(shè)備。
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script. (This does not work if the script is read from standard input, for the same reason as explained in the previous paragraph.)
使用腳本文件時(shí),經(jīng)常會(huì)運(yùn)行腳本然后進(jìn)入交互模式。這也可以通過在腳本之前加上 -i 參數(shù)來實(shí)現(xiàn)。(如果腳本來自標(biāo)準(zhǔn)輸入,就不能這樣運(yùn)行,與前一段提到的原因一樣。)
When known to the interpreter, the script name and additional
arguments thereafter are passed to the script in the variable
sys.argv
, which is a list of strings. Its length is at least
one; when no script and no arguments are given, sys.argv[0]
is
an empty string. When the script name is given as '-'
(meaning
standard input), sys.argv[0]
is set to '-'
. When
-c command is used, sys.argv[0]
is set to
'-c'
. Options found after -c command are
not consumed by the Python interpreter's option processing but left in
sys.argv
for the command to handle.
調(diào)用解釋器時(shí),腳本名和附加參數(shù)之傳入一個(gè)名為 sys.argv
的字符串列表。沒有腳本和參數(shù)時(shí),它至少也有一個(gè)元素:
sys.argv[0]
此時(shí)為空字符串。腳本名指定為 '-'
(表示標(biāo)準(zhǔn)輸入)時(shí), sys.argv[0]
被設(shè)置為'-'
,使用
-c 指令 時(shí), sys.argv[0]
被設(shè)定為'-c'
。 -c 命令之后的參數(shù)不會(huì)被
Python 解釋器的選項(xiàng)處理機(jī)制所截獲,而是留在sys.argv
中,供腳本命令操作。
When commands are read from a tty, the interpreter is said to be
in interactive mode. In this mode it prompts for the next
command with the primary prompt, usually three greater-than
signs (">>
> "); for continuation lines it prompts with
the secondary prompt, by default three dots ("... ").
The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:
從 tty 讀取命令時(shí),我們稱解釋器工作于 交互模式
。這種模式下它根據(jù) 主提示符
來執(zhí)行,主提示符通常標(biāo)識(shí)為三個(gè)大于號(hào)( ">>
> "
);繼續(xù)的部分被稱為 從屬提示符 ,由三個(gè)點(diǎn)標(biāo)識(shí)(
"... "
)。在第一行之前,解釋器打印歡迎信息、版本號(hào)和授權(quán)提示:
python Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>>
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
輸入多行結(jié)構(gòu)時(shí)需要從屬提示符了,例如,下面這個(gè) if 語句:
>>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" ... Be careful not to fall off!
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; 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 the executed commands is written to standard output.
有錯(cuò)誤發(fā)生時(shí),解釋器打印一個(gè)錯(cuò)誤信息和棧跟蹤器。交互模式下,它返回主提示符,如果從文件輸入執(zhí)行,它在打印棧跟蹤器后以非零狀態(tài)退出。(異?梢杂 try 語句中的 except 子句來控制,這樣就不會(huì)出現(xiàn)上文中的錯(cuò)誤信息)有一些非常致命的錯(cuò)誤會(huì)導(dǎo)致非零狀態(tài)下退出,這由通常由內(nèi)部矛盾和內(nèi)存溢出造成。所有的錯(cuò)誤信息都寫入標(biāo)準(zhǔn)錯(cuò)誤流;命令中執(zhí)行的普通輸出寫入標(biāo)準(zhǔn)輸出。
Typing the interrupt character (usually Control-C or DEL) to the primary or secondary prompt cancels the input and returns to the primary prompt.2.1 Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement.
在主提示符或附屬提示符輸入中斷符(通常是Control-C or DEL)就會(huì)取消當(dāng)前輸入,回到主命令行。 2.2.執(zhí)行命令時(shí)輸入一個(gè)中斷符會(huì)拋出一個(gè) KeyboardInterrupt 異常,它可以被 try 句截獲。
On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
BSD類的 Unix系統(tǒng)中,Python 腳本可以像 Shell 腳本那樣直接執(zhí)行。只要在腳本文件開頭寫一行命令,指定文件和模式:
#! /usr/bin/env python
(assuming that the interpreter is on the user's PATH) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python.
(將用戶路徑通知解釋器) "#!" 必須是文件的前兩個(gè)字符,在某些平臺(tái)上,第一行必須以 Unix 風(fēng)格的行結(jié)束符("\n")結(jié)束,不能用Mac("\ r")或Windows("\r\ n")的結(jié)束符。注意,"#"是Python中是行注釋的起始符。
The script can be given a executable mode, or permission, using the chmod command:
腳本可以通過 chmod 命令指定執(zhí)行模式和許可權(quán)。
$ chmod +x myscript.py
It is possible to use encodings different than ASCII in Python source
files. The best way to do it is to put one more special comment line
right after the #!
line to define the source file encoding:
Python 的源文件可以通過編碼使用 ASCII 以外的字符集。
最好的做法是在 #!
行后面用一個(gè)特殊的注釋行來定義字符集。
# -*- coding: iso-8859-1 -*-
With that declaration, all characters in the source file will be treated as
iso-8859-1
, and it will be
possible to directly write Unicode string literals in the selected
encoding. The list of possible encodings can be found in the
Python Library Reference, in the section
on codecs.
根據(jù)這個(gè)聲明,Python 會(huì)將文件中的字符盡可能的從指定的編碼轉(zhuǎn)為 Unicode,在本例中,這個(gè)字符集是 iso-8859-1 。在 Python 庫參考手冊(cè) 中 codecs部份可以找到可用的編碼列表(根據(jù)個(gè)人經(jīng)驗(yàn),推薦使用 cp-936或utf-8處理中文--譯者注)。
If your editor supports saving files as UTF-8
with a UTF-8
byte order mark (aka BOM), you can use that instead of an
encoding declaration. IDLE supports this capability if
Options/General/Default Source Encoding/UTF-8
is set. Notice
that this signature is not understood in older Python releases (2.2
and earlier), and also not understood by the operating system for
#!
files.
如果你的文件編輯器支持 UTF-8
格式,并且可以保存
UTF-8
標(biāo)記(aka BOM - Byte Order
Mark),你可以用這個(gè)來代替編碼聲明。IDLE可以通過設(shè)定Options/General/Default
Source Encoding/UTF-8
來支持它。需要注意的是舊版Python不支持這個(gè)標(biāo)記(Python
2.2或更早的版本),同樣支持#!
文件的操作系統(tǒng)也不會(huì)支持它(即#!
和
# -*- coding: -*- 二者必?fù)衿湟弧g者)。
By using UTF-8 (either through the signature or an encoding declaration), characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCIIcharacters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
使用 UTF-8 內(nèi)碼(無論是用標(biāo)記還是編碼聲明),我們可以在字符串和注釋中使用世界上的大部分語言。標(biāo)識(shí)符中不能使用非 ASCII 字符集。為了正確顯示所有的字符,你一定要在編輯器中將文件保存為 UTF-8 格式,而且要使用支持文件中所有字符的字體。
When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.
使用 Python 解釋器的時(shí)候,我們可能需要在每次解釋器啟動(dòng)時(shí)執(zhí)行一些命令。你可以在一個(gè)文件中包含你想要執(zhí)行的命令,設(shè)定一個(gè)名為 PYTHONSTARTUP 的環(huán)境變量來指定這個(gè)文件。這類似于 Unix shell的 .profile 文件。
This file is only read in interactive sessions, not when Python reads
commands from a script, and not when /dev/tty is given as the
explicit source of commands (which otherwise behaves like an
interactive session). It is executed in the same namespace where
interactive commands are executed, so that objects that it defines or
imports can be used without qualification in the interactive session.
You can also change the prompts sys.ps1
and sys.ps2
in
this file.
這個(gè)文件在交互會(huì)話期是只讀的,當(dāng) Python 從腳本中解讀文件或以終端
/dev/tty
做為外部命令源時(shí)則不會(huì)如此(盡管它們的行為很像是處在交互會(huì)話期。)它與解釋器執(zhí)行的命令處在同一個(gè)命名空間,所以由它定義或引用的一切可以在解釋器中不受限制的使用。你也可以在這個(gè)文件中改變
sys.ps1
和 sys.ps2
指令。
If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like "if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')". If you want to use the startup file in a script, you must do this explicitly in the script:
如果你想要在當(dāng)前目錄中執(zhí)行附加的啟動(dòng)文件,可以在全局啟動(dòng)文件中加入類似以下的代碼: "if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')"。 如果你想要在某個(gè)腳本中使用啟動(dòng)文件,必須要在腳本中寫入這樣的語句:
import os filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): execfile(filename)