The Python Tutorial 3.2-2使用Python解释器

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


2.1. Invoking the Interpreter(调用解释器)

The Python interpreter is usually installed as /usr/local/bin/python3.2 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

python3.2

to the shell. [1] 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/bin/python3.2 目录下。将 /usr/local/bin 目录放置到Unix shell的搜索路径里,以确保可以通过输入:

python3.2

命令来启动它。 [1] 由于Python解释器的安装路径是可选的,这也可能是其他路径,你可以联系当地的Python专家或系统管理员进行确认。(例如, /usr/local/python 就是一个常见的目录选择)

On Windows machines, the Python installation is usually placed in C:\Python32, though you can change this when you’re running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box:

set path=%path%;C:\python32

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 command: quit().

在Windows机器上,Python通常安装在 C:\Python32 位置,当然你可以在运行安装程序时修改安装位置。要想把此目录添加到你的PATH环境变量中,你可以在DOS窗口中输入以下命令:

set path=%path%;C:\python32

在主提示符(命令窗口)输入一个文件结束符(Unix系统是 Control-D ,Windows系统是 Control-Z )让解释器以0状态码退出。如果没有作用,你可以通过输入 quit() 命令退出解释器。

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 Interactive Input Editing and History Substitution 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.

Python解释器的行编辑功能也不复杂。在Unix系统上,任何Python解释器都可能已经添加了GNU readline库支持,这样就具备了完美的交互编辑和历史记录等功能。在第一个Python提示符中输入Control-P可以快速地检查是否支持命令行编辑。如果发出哔哔声,则说明你可以使用命令行编辑功能;更多快捷键的介绍请参考附录Interactive Input Editing and History Substitution 交互式输入编辑和历史记录 。如果没有任何声音,或者显示 ^P 字符,则说明命令行编辑功能不可用;你只能使用退格键(backspace)来删除当前行的字符。

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.

Python解释器操作与Unix shell有些类似:通过在终端设备(tty)使用标准输入启用解释器时,它交互地解释并执行命令;当使用文件名参数或以文件作为标准输入调用时,它读取文件并将文件作为脚本执行。

A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) incommand, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quotecommand in its entirety with single quotes.

第二种启动Python解释器的方法是 python -c command [arg] ... ,这种方法可以在命令行 执行Python语句,类似于shell中的 -c 选项。由于Python语句通常会包含空格或其他特殊shell字符,一般建议将命令用单引号引起来。

Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file formodule as if you had spelled out its full name on the command line.

有一些Python模块也可以当作脚本使用。你可以使用 python -m module [arg] ... 命令调用它们,这类似在命令行中键入完整的路径名执行模块 源文件一样。

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 turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys. The length of the list 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'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.

运行解释器时,脚本名和其后附带的参数通过字符窜列表变量 sys.argv 传递给脚本。你可能过import sys来访问这个列表。如果没有传递脚本和任何参数时,它至少有一个空字符串元素 sys.argv[0] 。当脚本名为 '-' (意指标准输入)时, sys.argv[0] 的值为 '-' 。当使用 -c 命令 时, sys.argv[0] 的值为 '-c' 。当使用 -m 模块 时, sys.argv[0] 的值为完整的模块地址名。在 -c 命令 或 -m 模块 之后的命令选项不会被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解释器工作在 交互模式 中。在此模式下它通过 主提示符 提示下一个命令,通常为三个大于号( >>> );对于连续的行通过 次提示符 提示,默认为三个点号( ... )。解释器在第一行提示符之前会输出一条欢迎信息说明它的版本号和版权提示.

$ python3.2
Python 3.2 (py3k, Sep 12 2007, 12:21:02)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

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 executed commands is written to standard output.

在错误发生时,Python解释器会打印出错误信息及其栈跟踪信息。在交互模式下,它将返回主提示符;如果是从文件输入,它将在打印出栈跟踪信息后以非零状态退出。( 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] Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement.

在主提示符或从提示符下输入中断字符(通常是Control-C或DEL)就会取消输入并回到主提示符。[2] 在执行命令时输入中断字符将抛出 KeyboardInterrupt 异常,你可以通过 try 语句捕获。

2.2.2. Executable Python Scripts(可执行的Python脚本)

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

#! /usr/bin/env python3.2

(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 Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a comment in Python.

在BSD类Unix系统中,只要在Python脚本首行输入以下文本行(要确认Python解释器路径包含在用户 PATH 变量中)并赋予文件可执行权限就能使其像Shell脚本一样直接运行:

#! /usr/bin/env python3.2

#! 必须是文件的前两个字符。在某些平台上,首行必须以Unix行结束符( '\n' )结束,而不能是Windows行结束符( '\r\n' )。注意 '#' 符号是Python注释的起始符。

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

$ chmod +x myscript.py

On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.

在Windows系统上,并没有“执行模式”的概念。 Python安装程序会用 python.exe 自动关联 .py 文件,当双击某个Python文件时就可以将其作为脚本运行了。文件扩展名也可以是 .pyw ,在这种情况下,通常出现的终端窗口将被禁用。

2.2.3. Source Code Encoding(源代码编码)

By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. 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.

默认情况下,Python源文件是UTF-8编码。在此编码下,全世界大多数语言的字符可以同时用在字符串、标识符和注释中 — 尽管Python标准库仅使用ASCII字符做为标识符,这只是任何可移植代码应该遵守的约定。如果要正确的显示所有的字符,你的编辑器必须能识别出文件是UTF-8编码,并且它使用的字体能支持文件中所有的字符。

It is also possible to specify a different encoding for source files. In order to do this, put one more special comment line right after the #! line to define the source file encoding:

# -*- coding: encoding -*-

With that declaration, everything in the source file will be treated as having the encoding "encoding" instead of UTF-8. The list of possible encodings can be found in the Python Library Reference, in the section on codecs.

你也可以为源文件指定不同的字符编码。为此,在 #! 行(首行)后插入至少一行特殊的注释行来定义源文件的编码。

# -*- coding: encoding -*-

通过此声明,源文件中所有的东西都会被当做用 encoding 指代的UTF-8编码对待。在Python库参考手册 codecs 一节中你可以找到一张可用的编码列表。

For example, if your editor of choice does not support UTF-8 encoded files and insists on using some other encoding, say Windows-1252, you can write:

# -*- coding: cp-1252 -*-

and still use all characters in the Windows-1252 character set in the source files. The special encoding comment must be in the first or second line within the file.

例如,如果你的编辑器不支持UTF-8编码的文件,但支持像Windows-1252的其他一些编码,你可以定义:

# -*- coding: cp-1252 -*-

这样就可以在源文件中使用Windows-1252字符集中的所有字符了。这个特殊的编码注释必须在文件中的 第一或第二 行定义。

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时,通常在每次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.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'): exec(open('.pythonrc.py').read()). 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'): exec(open('.pythonrc.py').read()) 代码编程实现。如果你想在某个脚本中使用启动文件,必须在脚本中明确的执行以下代码:

import os
filename =os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename): 
       exec(open(filename).read())
2.2.5. The Customization Modules(定制模块)

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:

Python提供了两种hooks来用于定制模块:sitecustomize和usercustomize。为了了解工作原理,你首先需要查明site-packages目录位置,启用Python运行如下代码:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.2/site-packages'

Now you can create a file named usercustomize.py in that directory and put anything you want in it. It will affect every invocation of Python, unless it is started with the -s option to disable the automatic import.

现在你可以在此目录下创建一个名称为"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.

sitecustomize使用同样方式工作,但它一般被管理员创建,放置在全局的site-packages目录中,它在usercustomize之前被导入。参见文档中site模块获取更多信息。

Footnotes(脚注)

[1] On Unix, the Python 3.x interpreter is by default not installed with the executable named python, so that it does not conflict with a simultaneously installed Python 2.x executable.

[1]在Unix系统上,Python 3.x解释器默认不会安装命名为python执行文件,所以它不会与同时已安装在系统中的Python 2.x命令冲突。

[2] A problem with the GNU Readline package may prevent this.

[2]可能存在GNU Readline包禁止此功能的问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值