查看“Python 官方简明教程 2”的源代码
来自Ubuntu中文
←
Python 官方简明教程 2
跳到导航
跳到搜索
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
=— 2. 使用Python解释器(未翻译,欢迎大家参与翻译)= ==— 2.1. 调用解释器 Invoking the Interpreter== Python解释器通常被安装在 /usr/local/bin/python3.2 那样的 Unix/Linux 机器有效路径(目录)上。把搜索路径 /usr/local/bin 添加到您的Unix操作系统 shell 命令的搜索路径里,这样您就可以通过 shell 终端输入下面的命令来启动 Python 。[注解 1.] 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 to the shell. [1] python3.2 由于可以在安装选项中选择放置解释器的目录,所以可以把Python安装在其它地方;请咨询您当地的 Pyhton 高手或系统管理员。(例如,/usr/local/python 也是一个常用的可选目录) 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.) 在 Windows 机器上,Python 通常被安装在 C:\Python32 目录,您也可以在安装过程中改变这个目录。如果要把这个目录添加到您的系统路径中,您可以在 DOS 对话框的命令提示符后面输入以下命令: 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 在主提示符后键入文件结束字符(Unix下是 Control-D,Windows下是 Control-Z),这将会以清零状态退出解释器。如果没有生效,您可以通过输入以下命令退出解释器:quit() 。 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(). 解释器的行编辑特性通常不太强大。在Unix上,无论是谁都可以安装能启用支持GNU readline 库的解释器,它增加了更多精巧的交互编辑和历史记录功能。要查看是否支持命令行编辑,也许最快的方法是在您看到的第一行Python提示符后输入 Control-P 。如果它发出蜂鸣声,你可以使用命令行编辑(请参考关于快捷键的介绍《附录:交互式输入编辑和历史替换》);如果没有任何反应,或者显示出 ^P ,则命令行编辑不可用;您只能使用退格键删除当前行的字符。 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. 解释器的操作有些像Unix shell:当呼叫来自一个连接于tty设备的标准输入,解释器读取并互动执行命令;当呼叫来自标准输入的文件名参数或者一个文件,解释器读取并执行该文件内的脚本。 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 -c command [arg] ...,该命令执行的参数,类似于shell的 -c 选项。由于Python参数经常包括空格或其它对于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 usually advised to quote command in its entirety with single quotes. 某些Python模块作为脚本也很有用。它们可以通过以下命令调用:python -m module [arg] ...,如果您在命令行里拼写出模块的全名,解释器将调用执行模块的源文件。 Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file for module as if you had spelled out its full name on the command line. 当一个脚本被调用,它有时能很有效地在进入交互模式之后运行脚本。通过在脚本前传递 -i 参数来实现。(如果脚本是从标准输入读取的,则不会生效,原因同上文所述) 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.) ===— 2.1.1. 传递参数 Argument Passing=== 当解释器读取了命令,脚本名稳及其后面的附加参数被转换为一个字符串列表,分配到sys模块的argv变量中。您可以通过执行导入sys访问这个列表。列表的长度至少是一;当没有给出脚本和参数时,sys.argv[0] 是一个空字符串。当给出了脚本名称是“-”时(意思是标准输入),sys.argv[0] 被设置为“-”。当使用了 -c 命令时,sys.argv[0] 被设置为“-c”。当使用了 -m 模块时,sys.argv[0] 被设置为所指定的模块的完整名称。在 -c 命令或 -m 模块之后的选项不会经由Python解释器的选项处理,但会保留在 sys.argv 中由命令或模块来处理。 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. ===— 2.1.2. 交互模式 teractive Mode=== 从tty设备读取了命令之后,解释器进入交互模式。在这个模式里,解释器用主提示符来提示下一个命令,通常是三个大于号(>>>);第二种是续行提示,默认是三个点号(...)。解释器在第一个提示符前打印一条欢迎信息、版本号和版权声明: 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: $ 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. >>> 当键入一个多行结构时,续行是必须的。作为一个例子,看看这个 if 语句: Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement: >>> 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=== 当发生一个错别时,解释器打印一个错误信息和一个堆栈跟踪。在交互模式犀,解释器返回主提示符;如果输入来自一个文件,解释器在打印一个堆栈跟踪后以非零状态退出。(在此情况下,除了第一个 try 语句是个例外,不会出现错误。)一些绝对致命的错误会引发无条件的非零退出;内在冲突和内存溢出也是同样的情况。所有的出错信息被写入标准错误流;通常由被执行的命令写入标准输出。 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. 在主提示符或第二提示符键入中断字符(通常是 Control-C 或 DEL 键),这将取消输入并返回主提示符。[注 2.]中断一个正在执行的命令(例如 try 语句)会引发 KeyboardInterrupt (键盘中断)异常。 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. ===— 2.2.2. 运行Python脚本 Executable Python Scripts=== 在BSD类的UNIX系统上,Python脚本可以直接执行,就像shell脚本一样,(假设解释器位于用户路径上)只需在脚本的开头加入一行: On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line #! /usr/bin/env python3.2 这样就能赋予文件可执行模式。符号 #! 必须是文件头两个字符。在一些平台上,第一行必须以Unix类型的行结束符(“\n”)而不是Windows的(“\r\n”)来结束。请注意,哈希字符、或英镑符,“#”,在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 Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a comment in Python. Unix/Linux下使用 chmod 命令来赋予脚本一个可执行模式的文件权限: The script can be given an executable mode, or permission, using the chmod command: $ chmod +x myscript.py 在Windows下,没有“可执行模式”的概念。Python安装程序自动关联后缀及是 .py的文件到 python.exe 上,所以只要双击一个Python文件就能运行这个脚本。这也扩展到 .pyw文件,通常会出现的控制台窗口在这种情况下将被隐藏。 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. ===— 2.2.3. 源代码编码 Source Code Encoding=== 默认的,Python源文件对应的编码是UTF-8。在这个编码下,在世界上的大部分语言可以使用相同的字符串,识别码和注释——虽然标准库只使用ASCII字符识别这项任何可移植代码应该遵循的公约。为了正确地显示所有的字符,你的编辑器必须能辨认UTF-8编码,而且必须在文件中使用支持所有字符的字体。 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. 也可以为源文件指定不同的编码。为了做到这一点,在 #! 行之后添加一个用于限定源文件编码的相当特殊的注释行: 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 -*- 在上面的例子中,源文件的所有东西都将被转换为encoding编码而不是UTF-8编码。可用的编码请参考《Python库参考》的编码部分 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. 例如,如果您选择的编辑器不支持UTF-8编码文件,而且只使用其他编码,诸如Windows-1252,您可以这样写: 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 -*- 这将仍然在源文件中使用Windows- 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. ===— 2.2.4. 交互启动文件 The Interactive Startup File=== 当您在每次解释器启动后以交互模式使用Python时,常常需要手动执行一些标准命令。您可以通过向启动命令中包含的文件名设置名为 PYTHONSTARTUP 的环境变量来实现。文类似于在Unix系统中为Shell而设定的 .profile 文件特性。 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在脚本中读取命令的时候文件是只读的,也不是在命令源代码明确给出 /dev/tty 的时候文件是只读的(否则其表现就像一个交互对话)。 这是执行在交互命令执行处执行同一个命名空间,这样就能在没有交互对话限定下进行定义和导入事项。您也可以改变这个文件的 sys.ps1 和 sys.ps2 提示符。 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. 如果您想要从当前目录读取一个额外的启动文件,您可以在全局启动文件中使用像 os.path.isfile(“.pythonrc.py”)这样的代码来编程:exec(open('.pythonrc.py').read()) 。如果您打算在脚本中使用启动文件,你必须在脚本中明确地这样做: 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: import os filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): exec(open(filename).read()) '''附录:''' Footnotes #在Unix上,Python 3.x 解释器默认不会由名称是python的可执行文件来安装,所以这不会和安装 Python 2.x 的可执行文件相冲突。 [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. #一个与GNU Readline包的问题可以避免这惬况 [2] A problem with the GNU Readline package may prevent this. '''<center>————— [[Python_官方简明教程|返回《 Python 官方简明教程 》目录]] —————</center>''' '''<center>—— [[编程语言|返回《 Python 手册 》总目录]] ——</center>'''
返回
Python 官方简明教程 2
。
导航菜单
页面操作
页面
讨论
阅读
查看源代码
历史
页面操作
页面
讨论
更多
工具
个人工具
登录
导航
首页
最近更改
随机页面
页面分类
帮助
搜索
编辑
编辑指南
沙盒
新闻动态
字词处理
工具
链入页面
相关更改
特殊页面
页面信息