8. Componentes de Alto-Nível

O interpretador Python pode receber suas entradas de uma quantidade de fontes: de um script passado a ele como entrada padrão ou como um argumento do programa, digitado interativamente, de um arquivo fonte de um módulo, etc. Este capítulo mostra a sintaxe usada nesses casos.

8.1. Programas Python completos

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.

A sintaxe para um programa Python completo é esta para uma entrada de arquivo, descrita na próxima seção.

O interpretador também pode ser invocado no modo interativo; neste caso, ele não lê e executa um programa completo, mas lê e executa uma instrução (possivelmente composta) por vez. O ambiente inicial é idêntico àquele de um programa completo; cada instrução é executada no espaço de nomes 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. Entrada de arquivo

Toda entrada lida de arquivos não-interativos têm a mesma forma:

file_input ::=  (NEWLINE | statement)*

Essa sintaxe é usada nas seguintes situações:

  • quando analisando um programa Python completo (a partir de um arquivo ou de uma string);

  • quando analisando um módulo;

  • when parsing a string passed to the exec statement;

8.3. Entrada interativa

A entrada em modo interativo é analisada usando a seguinte gramática:

interactive_input ::=  [stmt_list] NEWLINE | compound_stmt NEWLINE

Note que uma instrução composta (de alto-nível) deve ser seguida por uma linha em branco no modo interativo; isso é necessário para ajudar o analisador sintático a detectar o fim da entrada.

8.4. Entrada de expressão

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.