9. Top-level components顶级组件¶
The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. Python解释器可以从多个源获取输入:从作为标准输入或作为程序参数传递给它的脚本,以交互方式键入,从模块源文件等。This chapter gives the syntax used in these cases.本章给出了这些情况下使用的语法。
9.1. Complete Python programs完成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. 虽然语言规范不需要规定如何调用语言解释器,但有一个完整Python程序的概念是很有用的。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 一个完整的Python程序是在一个最低限度初始化的环境中执行的:所有内置和标准模块都可用,但除了sys
(various system services), builtins
(built-in functions, exceptions and None
) and __main__
. sys
(各种系统服务)、builtins
(内置函数、异常和None
)和__main__
之外,没有任何模块已初始化。The latter is used to provide the local and global namespace for execution of the complete program.后者用于为整个程序的执行提供本地和全局命名空间。
The syntax for a complete Python program is that for file input, described in the next section.完整Python程序的语法是用于文件输入的语法,将在下一节中介绍。
The interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement (possibly compound) at a time. 解释器也可以在交互模式下调用;在这种情况下,它不会读取并执行一个完整的程序,而是一次读取并执行一条语句(可能是复合语句)。The initial environment is identical to that of a complete program; each statement is executed in the namespace of 初始环境与完整程序的环境相同;每个语句都在__main__
.__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. -c
字符串命令行选项、作为第一个命令行参数传递的文件或作为标准输入。If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program.如果文件或标准输入为tty设备,口译员进入交互模式;否则,它会将文件作为一个完整的程序执行。
9.2. File input文件输入¶
All input read from non-interactive files has the same form:从非交互式文件读取的所有输入具有相同的形式:
file_input ::= (NEWLINE |statement
)*
This syntax is used in the following situations:此语法用于以下情况:
9.3. Interactive input交互式输入¶
Input in interactive mode is parsed using the following grammar:使用以下语法分析交互式模式中的输入:
interactive_input ::= [stmt_list
] NEWLINE |compound_stmt
NEWLINE
Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.注意,在交互模式下,(顶层)复合语句后面必须跟一个空行;这有助于解析器检测输入的结束。
9.4. Expression input表达式输入¶
eval()
is used for expression input. 用于表达式输入。It ignores leading whitespace. 它忽略前导空格。The string argument to eval()
must have the following form:eval()
的字符串参数必须具有以下格式:
eval_input ::=expression_list
NEWLINE*