Subsections


2. 使用Python解释器 Using the Python Interpreter


2.1 调用解释器 Invoking the Interpreter

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 的解释器被安装在目标机器的 /usr/local/bin/python 目录下;把 /usr/local/bin 目录放进你的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.)

来启动。因为安装路径是可选的,所以也有可能安装在其它位置,你可以与安装 Python 的用户或系统管理员联系。(例如,/usr/local/python就是一个很常见的选择)

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()".

输入一个文件结束符(Unix 上是Ctrl+D,Windows上是Ctrl+Z)解释器会以0值退出(就是说,没有什么错误,正常退出--译者)。如果这没有起作用,你可以输入以下命令退出:"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 for an introduction to the keys. If nothing appears to happen, or if P is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line.

解释器的行编辑功能并不很复杂。装在Unix上的解释器可能会有GNU readline 库支持,这样就可以额外得到精巧的交互编辑和历史记录功能。可能检查命令行编辑器支持能力最方便的方式是在主提示符下输入Ctrl-P。如果有嘟嘟声(计算机扬声器),说明你可以使用命令行编辑功能,从附录 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:使用终端设备做为标准输入来调用它时,解释器交互的解读和执行命令,通过文件名参数或以文件做为标准输入设备时,它从文件中解读并执行脚本

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.

启动解释器的第二个方法是"python -c command [arg] ...",这种方法可以在命令行中直接执行语句,等同于Shell的 -c选项。因为Python语句通常会包括空格之类的特殊字符,所以最好把整个语句用双引号包起来。

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"是有区别的。对于后一种情况,程序中类似于调用 input()raw_input() 这样的输入请求,来自于确定的文件。因为在解析器开始执行之前,文件已经完全读入,所以程序指向文件尾。在前一种情况(这通常是你需要的)它们从来自于任何联接到 Python 解释器的标准输入,无论它们是文件还是其它设备。

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.)

使用脚本文件时,经常会运行脚本然后进入交互模式。这也可以通过在脚本之前加上 -i 参数来实现。(如果脚本来自标准输入,就不能这样运行,与前一段提到的原因一样。)


2.1.1 参数传递 Argument Passing

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.

调用解释器时,脚本名和附加参数之传入一个名为 sys.argv 的字符串列表。没有脚本和参数时,它至少也有一个元素: sys.argv[0] 此时为空字符串。脚本名指定为 '-' (表示标准输入)时, sys.argv[0]被设置为'-',使用 -c 指令 时, sys.argv[0] 被设定为'-c'-c 命令之后的参数不会被 Python 解释器的选项处理机制所截获,而是留在sys.argv 中,供脚本命令操作。


2.1.2 交互模式 Interactive Mode

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 读取命令时,我们称解释器工作于 交互模式 。这种模式下它根据 主提示符 来执行,主提示符通常标识为三个大于号( ">>" );继续的部分被称为 从属提示符 ,由三个点标识( "... " )。在第一行之前,解释器打印欢迎信息、版本号和授权提示:

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:

输入多行结构时需要从属提示符了,例如,下面这个 if 语句:

>>> the_world_is_flat = 1
>>> if the_world_is_flat:
...     print "Be careful not to fall off!"
...
Be careful not to fall off!


2.2 解释器及其环境 The Interpreter and Its Environment


2.2.1 错误处理 Error Handling

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.

有错误发生时,解释器打印一个错误信息和栈跟踪器。交互模式下,它返回主提示符,如果从文件输入执行,它在打印栈跟踪器后以非零状态退出。(异常可以由 try 语句中的 except 子句来控制,这样就不会出现上文中的错误信息)有一些非常致命的错误会导致非零状态下退出,这由通常由内部矛盾和内存溢出造成。所有的错误信息都写入标准错误流;命令中执行的普通输出写入标准输出。

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)就会取消当前输入,回到主命令行。 2.2.执行命令时输入一个中断符会抛出一个 KeyboardInterrupt 异常,它可以被 try 句截获。


2.2.2 执行Python脚本 Executable Python Scripts

On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line

BSD类的 Unix系统中,Python 脚本可以像 Shell 脚本那样直接执行。只要在脚本文件开头写一行命令,指定文件和模式:

#! /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.

(将用户路径通知解释器) "#!" 必须是文件的前两个字符,在某些平台上,第一行必须以 Unix 风格的行结束符("\n")结束,不能用Mac("\ r")或Windows("\r\ n")的结束符。注意,"#"是Python中是行注释的起始符。

The script can be given a executable mode, or permission, using the chmod command:

脚本可以通过 chmod 命令指定执行模式和许可权。

$ chmod +x myscript.py

2.2.3 源程序编码 Source Code Encoding

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 以外的字符集。 最好的做法是在 #! 行后面用一个特殊的注释行来定义字符集。

# -*- 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.

根据这个声明,Python 会将文件中的字符尽可能的从指定的编码转为 Unicode,在本例中,这个字符集是 iso-8859-1 。在 Python 库参考手册codecs部份可以找到可用的编码列表(根据个人经验,推荐使用 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 标记(aka BOM - Byte Order Mark),你可以用这个来代替编码声明。IDLE可以通过设定Options/General/Default Source Encoding/UTF-8 来支持它。需要注意的是旧版Python不支持这个标记(Python 2.2或更早的版本),同样支持#!文件的操作系统也不会支持它(即#!和 # -*- coding: -*- 二者必择其一——译者)。

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 内码(无论是用标记还是编码声明),我们可以在字符串和注释中使用世界上的大部分语言。标识符中不能使用非 ASCII 字符集。为了正确显示所有的字符,你一定要在编辑器中将文件保存为 UTF-8 格式,而且要使用支持文件中所有字符的字体。


2.2.4 交互式环境的启动文件 The Interactive Startup File

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 解释器的时候,我们可能需要在每次解释器启动时执行一些命令。你可以在一个文件中包含你想要执行的命令,设定一个名为 PYTHONSTARTUP 的环境变量来指定这个文件。这类似于 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.

这个文件在交互会话期是只读的,当 Python 从脚本中解读文件或以终端 /dev/tty 做为外部命令源时则不会如此(尽管它们的行为很像是处在交互会话期。)它与解释器执行的命令处在同一个命名空间,所以由它定义或引用的一切可以在解释器中不受限制的使用。你也可以在这个文件中改变 sys.ps1sys.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:

如果你想要在当前目录中执行附加的启动文件,可以在全局启动文件中加入类似以下的代码: "if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')"。 如果你想要在某个脚本中使用启动文件,必须要在脚本中写入这样的语句:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    execfile(filename)



Footnotes

... prompt.2.1
A problem with the GNU Readline package may prevent this.
... DEL)就会取消当前输入,回到主命令行。2.2
GNU readline 包的一个错误可能会造成无法正常工作。
译者:刘鑫(march.liu AT gmail DOT com) 由:limodou转(limodou AT gmail DOT com)
See About this document... for information on suggesting changes.