内容表

  • 9. 顶层组件
    • 9.1. 完整 Python 程序
    • 9.2. 文件输入
    • 9.3. 交互输入
    • 9.4. 表达式输入

上一话题

8. 复合语句

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 语言参考
  8. 9. 顶层组件

9. 顶层组件 ¶

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. This chapter gives the syntax used in these cases.

9.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), builtins (built-in functions, exceptions and 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.

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__ .

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.

9.2. 文件输入 ¶

All input read from non-interactive files has the same form:

file_input ::=  (NEWLINE | statement)*
									

This syntax is used in the following situations:

  • when parsing a complete Python program (from a file or from a string);

  • 当剖析模块时;

  • when parsing a string passed to the exec() 函数;

9.3. 交互输入 ¶

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. 表达式输入 ¶

eval() is used for expression input. It ignores leading whitespace. The string argument to eval() must have the following form:

eval_input ::=  expression_list NEWLINE*
							

内容表

  • 9. 顶层组件
    • 9.1. 完整 Python 程序
    • 9.2. 文件输入
    • 9.3. 交互输入
    • 9.4. 表达式输入

上一话题

8. 复合语句

下一话题

10. 完整语法规范

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 语言参考
  8. 9. 顶层组件

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1