8. 最高层级组件

Python 解释器可以从多种源获得输入:作为标准输入或程序参数传入的脚本,以交互方式键入的语句,导入的模块源文件等等。 这一章将给出在这些情况下所用的语法。

8.1. 完整的 Python 程序

While a language specification need not prescribe how the language interpreter is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for sys (various system services), __builtin__ (built-in functions, exceptions and None) and __main__. The latter is used to provide the local and global namespace for execution of the complete program.

适用于一个完整 Python 程序的语法即下节所描述的文件输入。

解释器也可以通过交互模式被发起调用;在此情况下,它并不读取和执行一个完整程序,而是每次读取和执行一条语句(可能为复合语句)。 此时的初始环境与一个完整程序的相同;每条语句会在 __main__ 的命名空间中被执行。

A complete program can be passed to the interpreter in three forms: with the -c string command line option, as a file passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program.

8.2. 文件输入

所有从非交互式文件读取的输入都具有相同的形式:

file_input ::=  (NEWLINE | statement)*

此语法用于下列几种情况:

  • 解析一个完整 Python 程序时(从文件或字符串);

  • 解析一个模块时;

  • when parsing a string passed to the exec statement;

8.3. 交互式输入

交互模式下的输入使用以下语法进行解析:

interactive_input ::=  [stmt_list] NEWLINE | compound_stmt NEWLINE

请注意在交互模式下一条(最高层级)复合语句必须带有一个空行;这对于帮助解析器确定输入的结束是必须的。

8.4. 表达式输入

There are two forms of expression input. Both ignore leading whitespace. The string argument to eval() must have the following form:

eval_input ::=  expression_list NEWLINE*

The input line read by input() must have the following form:

input_input ::=  expression_list NEWLINE

Note: to read ‘raw’ input line without interpretation, you can use the built-in function raw_input() or the readline() method of file objects.