8. Composants de plus haut niveau

L’entrée de l’interpréteur Python peut provenir d’un certain nombre de sources : d’un script passé en entrée standard ou en argument de programme, tapée de manière interactive, à partir d’un fichier source de module, etc. Ce chapitre donne la syntaxe utilisée dans ces différents cas.

8.1. Programmes Python complets

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.

La syntaxe d’un programme Python complet est celle d’un fichier d’entrée, dont la description est donnée dans la section suivante.

L’interpréteur peut également être invoqué en mode interactif ; dans ce cas, il ne lit et n’exécute pas un programme complet mais lit et exécute une seule instruction (éventuellement composée) à la fois. L’environnement initial est identique à celui d’un programme complet ; chaque instruction est exécutée dans l’espace de noms de __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. Fichier d’entrée

Toutes les entrées lues à partir de fichiers non interactifs sont de la même forme :

file_input ::=  (NEWLINE | statement)*

Cette syntaxe est utilisée dans les situations suivantes :

  • lors de l’analyse d’un programme Python complet (à partir d’un fichier ou d’une chaîne de caractères) ;

  • lors de l’analyse d’un module ;

  • when parsing a string passed to the exec statement;

8.3. Entrée interactive

L’entrée en mode interactif est analysée à l’aide de la grammaire suivante :

interactive_input ::=  [stmt_list] NEWLINE | compound_stmt NEWLINE

Notez qu’une instruction composée (de niveau supérieur) doit être suivie d’une ligne blanche en mode interactif ; c’est nécessaire pour aider l’analyseur à détecter la fin de l’entrée.

8.4. Entrée d’expression

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.