Python interview - Interpreter

Using the Python Interpreter 使用Python 解释器

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 就是一个很常见 的选择)

On Windows machines, the Python installation is usually placed in C:\Python27, 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

在 Windows机器上,Python 通常安装在 C:\Python27 当然,我们在运行安装程序的 时候可以改变它。需要把这个目录加入到我们的 Path 中的话,可以像下面这样 在 DOS 窗中输入命令行

set path=%path%;C:\\python27

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上是 Ctrl+D ,Windows上是 Ctrl+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.

解释器的行编辑功能并不很复杂。装在 Unix 上的解释器可能会有 GNU readline 库支持,这样就可以额外得到精巧的交互编辑和历史记录功能。可能检查命令行 编辑器支持能力。最方便的方式是在主提示符下输入 Control-P。如果有嘟嘟声(计算 机扬声器),说明你可以使用命令行编辑功能,从附录 Interactive Input Editing and History Substitution 可以查到快捷键的 介绍。如果什么声音也没有,或者显示 ^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 usually advised to quote command in its entirety with single quotes.

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

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.

有些 Python 模块也可以当作脚本使用。它们可以用 python -m module [arg]... 调用,这样就会像你在命令行中给出其完整名字一样运行 模块 源文件。

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. 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'. 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 的字符串列表。没有 给定脚本和参数时,它至少也有一个元素: sys.argv[0] 此时为空字符串。脚本 名指定为 '-' (表示标准输入)时, sys.argv[0] 被设定为 '-' ,使用 -c 指令时, sys.argv[0] 被设定为 '-c' 。 使用 -m module 参数时, sys.agv[0] 被设定 为指定模块的全名。:option:-c command 或者 -m module 之 后的参数不会被 Python 解释器的选项处理机制所截获,而是留在 sys.argv 中,供脚本命令操作。


3. 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 2.7 (#1, Feb 28 2010, 00:02:06)
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!

P.S. 注意需要自己打行前的空格


The Interpreter and Its Environment 解释器及其环境
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.

有错误发生时,解释器打印一个错误信息和栈跟踪器。交互模式下,它返回主提 示符,如果从文件输入执行,它在打印栈跟踪器后以非零状态退出。(异常可以 由 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. [1] Typing an interrupt while a command is executing raises theKeyboardInterrupt exception, which may be handled by a try statement.

在主提示符或附属提示符输入中断符(通常是Control-C 或者 DEL)就会取消当 前输入,回到主命令行。 [2] 2.2.执行命令时输入一个中断符会抛出一个 KeyboardInterrupt 异常,它可以被 try句截获。


2. Executable Python Scripts 可执行Python脚本

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

(要确认 Python 解释器在用户的 PATH 中) #! 必须是文件的前 两个字符,在某些平台上,第一行必须以 Unix 风格的行结束符( '\n' )结束, 不能用 Windows ( '\r\n' ) 的结束符。注意,'#' 是Python中是行 注释的起始符。

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

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

$ 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 安装程序自动将 .py 文件关 联到 python.exe ,所以在 Python 文件图标上双击,它就会作为脚本执行。 同样 .pyw 也作了这样的关联,通常它执行时不会显示控制台窗口。


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: encoding -*-

With that declaration, all characters in the source file will be treated as having the encoding encoding, 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 会尝试将文件中的字符编码转为 encoding 编码。并且,它 尽可能的将指定的编码直接写成 Unicode 文本。在 Python 库参考手册 中 codecs 部份可以找到可用的编码列表(推荐使用 utf-8 处理中文--译者注)。

For example, to write Unicode literals including the Euro currency symbol, the ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value 164. This script will print the value 8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit:

例如,可以用 ISO-8859-15 编码可以用来编写包含欧元符号的 Unicode 文本, 其编码值为 164。这个脚本会输出 8364 (欧元符号的 Unicode 对应编码) 然后退出

# -*- coding: iso-8859-15 -*-

currency = u"€"
print ord(currency)

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 SourceEncoding/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 script files with #! lines (only used on Unix systems).

如果你的文件编辑器可以将文件保存为 UTF-8 格式,并且可以保存 UTF-8 字节序标记 (即 BOM - Byte Order Mark),你可以用这个来代替编码声明。IDLE可以通过设定Options/General/Default Source Encoding/UTF-8 来支持它。需要注意的是旧 版 Python 不支持这个标记(Python 2.2或更早的版本),也同样不去理解由操 作系统调用脚本使用的 #! 行(仅限于 Unix系统)。

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 格式,而且要使用支持 文件中所有字符的字体。


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.ps1and 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'): 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)



参考:

https://docs.python.org/2/tutorial/interpreter.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值