📄 ctut.tex
字号:
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 \emph{script} from
that file.
解释器的操作有些像 \UNIX
Shell:使用终端设备做为标准输入来调用它时,解释器交互的解读和执行命令,通过文件名参数或以文件做为标准输入设备时,它从文件中解读并执行\emph{脚本}。
A second way of starting the interpreter is
\samp{\program{python} \programopt{-c} \var{command} [arg] ...}, which
executes the statement(s) in \var{command}, analogous to the shell's
\programopt{-c} option. Since Python statements often contain spaces
or other characters that are special to the shell, it is best to quote
\var{command} in its entirety with double quotes.
启动解释器的第二个方法是\samp{\program{python} \programopt{-c}
\var{command} [arg]
...},这种方法可以在命令行中直接执行语句,等同于Shell的
\programopt{-c}选项。因为Python语句通常会包括空格之类的特殊字符,所以最好把整个\var{语句}用双引号包起来。
Note that there is a difference between \samp{python file} and
\samp{python <file}. In the latter case, input requests from the
program, such as calls to \function{input()} and \function{raw_input()}, are
satisfied from \emph{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.
注意\samp{python file}和\samp{python
<file}是有区别的。对于后一种情况,程序中类似于调用
\function{input()}\function{raw_input()}
这样的输入请求,来自于确定的\emph{文件}。因为在解析器开始执行之前,文件已经完全读入,所以程序指向文件尾。在前一种情况(这通常是你需要的)它们从来自于任何联接到
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 \programopt{-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.)
使用脚本文件时,经常会运行脚本然后进入交互模式。这也可以通过在脚本之前加上
\programopt{-i}
参数来实现。(如果脚本来自标准输入,就不能这样运行,与前一段提到的原因一样。)
\subsection{参数传递 Argument Passing \label{argPassing}}
When known to the interpreter, the script name and additional
arguments thereafter are passed to the script in the variable
\code{sys.argv}, which is a list of strings. Its length is at least
one; when no script and no arguments are given, \code{sys.argv[0]} is
an empty string. When the script name is given as \code{'-'} (meaning
standard input), \code{sys.argv[0]} is set to \code{'-'}. When
\programopt{-c} \var{command} is used, \code{sys.argv[0]} is set to
\code{'-c'}. Options found after \programopt{-c} \var{command} are
not consumed by the Python interpreter's option processing but left in
\code{sys.argv} for the command to handle.
调用解释器时,脚本名和附加参数之传入一个名为 \code{sys.argv}
的字符串列表。没有脚本和参数时,它至少也有一个元素:
\code{sys.argv[0]} 此时为空字符串。脚本名指定为 \code{'-'}
(表示标准输入)时, \code{sys.argv[0]}被设置为\code{'-'},使用
\programopt{-c} \var{指令} 时, \code{sys.argv[0]}
被设定为\code{'-c'}。 \programopt{-c} \var{命令}之后的参数不会被
Python 解释器的选项处理机制所截获,而是留在\code{sys.argv}
中,供脚本命令操作。
\subsection{交互模式 Interactive Mode \label{interactive}}
When commands are read from a tty, the interpreter is said to be
in \emph{interactive mode}. In this mode it prompts for the next
command with the \emph{primary prompt}, usually three greater-than
signs (\samp{>\code{>}>~}); for continuation lines it prompts with
the \emph{secondary prompt}, by default three dots (\samp{...~}).
The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:
从 tty 读取命令时,我们称解释器工作于 \emph{交互模式}
。这种模式下它根据 \emph{主提示符}
来执行,主提示符通常标识为三个大于号( \samp{>\code{>}>~}
);继续的部分被称为 \emph{从属提示符} ,由三个点标识(
\samp{...~}
)。在第一行之前,解释器打印欢迎信息、版本号和授权提示:
\begin{verbatim}
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
>>>
\end{verbatim}
Continuation lines are needed when entering a multi-line construct.
As an example, take a look at this \keyword{if} statement:
输入多行结构时需要从属提示符了,例如,下面这个 \keyword{if}
语句:
\begin{verbatim}
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!
\end{verbatim}
\section{解释器及其环境 The Interpreter and Its Environment \label{interp}}
\subsection{错误处理 Error Handling \label{error}}
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 \keyword{except} clause in a
\keyword{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.
有错误发生时,解释器打印一个错误信息和栈跟踪器。交互模式下,它返回主提示符,如果从文件输入执行,它在打印栈跟踪器后以非零状态退出。(异常可以由
\keyword{try} 语句中的 \keyword{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.\footnote{
A problem with the GNU Readline package may prevent this.
} Typing an interrupt while a command is executing raises the
\exception{KeyboardInterrupt} exception, which may be handled by a
\keyword{try} statement.
在主提示符或附属提示符输入中断符(通常是Control-C or
DEL)就会取消当前输入,回到主命令行。 \footnote{GNU readline
包的一个错误可能会造成无法正常工作。}.执行命令时输入一个中断符会抛出一个
\exception{KeyboardInterrupt} 异常,它可以被 \keyword{try}
句截获。
\subsection{执行Python脚本 Executable Python Scripts \label{scripts}}
On BSD'ish \UNIX{} systems, Python scripts can be made directly
executable, like shell scripts, by putting the line
BSD类的 \UNIX{}系统中,Python 脚本可以像 Shell
脚本那样直接执行。只要在脚本文件开头写一行命令,指定文件和模式:
\begin{verbatim}
#! /usr/bin/env python
\end{verbatim}
(assuming that the interpreter is on the user's \envvar{PATH}) at
the beginning of the script and giving the file an executable
mode. The \samp{\#!} must be the first two characters of the
file. On some platforms, this first line must end with a
\UNIX-style line ending (\character{\e n}), not a Mac OS
(\character{\e r}) or Windows (\character{\e r\e n}) line ending.
Note that the hash, or pound, character, \character{\#}, is used
to start a comment in Python.
(将用户路径通知解释器) \samp{\#!}
必须是文件的前两个字符,在某些平台上,第一行必须以 \UNIX
风格的行结束符(\character{\e n})结束,不能用Mac(\character{\e
r})或Windows(\character{\e r\e
n})的结束符。注意,\character{\#}是Python中是行注释的起始符。
The script can be given a executable mode, or permission, using
the \program{chmod} command:
脚本可以通过 \program{chmod} 命令指定执行模式和许可权。
\begin{verbatim}
$ chmod +x myscript.py
\end{verbatim} % $ <-- bow to font-lock
\subsection{源程序编码 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 \code{\#!} line to define the source file encoding:
Python 的源文件可以通过编码使用 ASCII 以外的字符集。
最好的做法是在 \code{\#!} 行后面用一个特殊的注释行来定义字符集。
\begin{verbatim}
# -*- coding: iso-8859-1 -*-
\end{verbatim}
With that declaration, all characters in the source file will be treated as
{}\code{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
\citetitle[../lib/lib.html]{Python Library Reference}, in the section
on \ulink{\module{codecs}}{../lib/module-codecs.html}.
根据这个声明,Python 会将文件中的字符尽可能的从指定的编码转为
Unicode,在本例中,这个字符集是 iso-8859-1 。在
\citetitle[../lib/lib.html]{Python 库参考手册} 中
\ulink{\module{codecs}}{../lib/module-codecs.html}部份可以找到可用的编码列表(根据个人经验,推荐使用
cp-936或utf-8处理中文--译者注)。
If your editor supports saving files as \code{UTF-8} with a UTF-8
\emph{byte order mark} (aka BOM), you can use that instead of an
encoding declaration. IDLE supports this capability if
\code{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
\code{\#!} files.
如果你的文件编辑器支持 \code{UTF-8} 格式,并且可以保存
\code{UTF-8} 标记(\emph{aka BOM - Byte Order
Mark}),你可以用这个来代替编码声明。IDLE可以通过设定\code{Options/General/Default
Source Encoding/UTF-8}
来支持它。需要注意的是旧版Python不支持这个标记(Python
2.2或更早的版本),同样支持\code{\#!}文件的操作系统也不会支持它(即\code{\#!}和
\verb|# -*- 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-\ASCII characters 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 格式,而且要使用支持文件中所有字符的字体。
\subsection{交互式环境的启动文件 The Interactive Startup File \label{startup}}
% XXX This should probably be dumped in an appendix, since most people
% don't use Python interactively in non-trivial ways.
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
\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
commands. This is similar to the \file{.profile} feature of the
\UNIX{} shells.
使用 Python
解释器的时候,我们可能需要在每次解释器启动时执行一些命令。你可以在一个文件中包含你想要执行的命令,设定一个名为
\envvar{PYTHONSTARTUP} 的环境变量来指定这个文件。这类似于 Unix
shell的 \file{.profile} 文件。
This file is only read in interactive sessions, not when Python reads
commands from a script, and not when \file{/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 \code{sys.ps1} and \code{sys.ps2} in
this file.
这个文件在交互会话期是只读的,当 Python 从脚本中解读文件或以终端
\file{/dev/tty}
做为外部命令源时则不会如此(尽管它们的行为很像是处在交互会话期。)它与解释器执行的命令处在同一个命名空间,所以由它定义或引用的一切可以在解释器中不受限制的使用。你也可以在这个文件中改变
\code{sys.ps1} 和 \code{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 \samp{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:
如果你想要在当前目录中执行附加的启动文件,可以在全局启动文件中加入类似以下的代码:
\samp{if os.path.isfile('.pythonrc.py'):
execfile('.pythonrc.py')}。
如果你想要在某个脚本中使用启动文件,必须要在脚本中写入这样的语句:
\begin{verbatim}
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
\end{verbatim}
\chapter{Python简介 An Informal Introduction to Python \label{informal}}
In the following examples, input and output are distinguished by the
presence or absence of prompts (\samp{>\code{>}>~} and \samp{...~}): to repeat
the example, you must type everything after the prompt, when the
prompt appears; lines that do not begin with a prompt are output from
the interpreter. %
%\footnote{
% I'd prefer to use different fonts to distinguish input
% from output, but the amount of LaTeX hacking that would require
% is currently beyond my ability.
%}
Note that a secondary prompt on a line by itself in an example means
you must type a blank line; this is used to end a multi-line command.
在后面的例子中,区分输入和输出的方法是看是否有提示符(\samp{>>>~}
和\samp{...~}):想要重现这些例子的话,你就要在提示符显示后输入所有的一切;没有以提示符开始的行,是解释器输出的信息。需要注意的是示例中的从属提示符用于多行命令的结束,它表示你需要输入一个空行。
Many of the examples in this manual, even those entered at the
interactive prompt, include comments. Comments in Python start with
the hash character, \character{\#}, and extend to the end of the
physical line. A comment may appear at the start of a line or
following whitespace or code, but not within a string literal. A hash
character within a string literal is just a hash character.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -