8. 최상위 요소들

파이썬 인터프리터는 여러 가지 출처로부터 입력을 얻을 수 있다: 표준 입력이나 프로그램 인자로 전달된 스크립트, 대화형으로 입력된 것, 모듈 소스 파일 등등. 이 장은 이 경우들에 사용되는 문법을 제공한다.

8.1. 완전한 파이썬 프로그램

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.

완전한 파이썬 프로그램의 문법은 다음 섹션에서 설명되는 파일 입력의 경우다.

인터프리터는 대화형으로 실행될 수도 있다; 이 경우, 완전한 프로그램을 읽어서 실행하지 않고, 한 번에 한 문장 (복합문도 가능하다) 씩 읽어서 실행한다. 초기 환경은 완전한 프로그램과 같다; 각 문장은 __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)*

이 문법은 다음과 같은 상황에서 사용된다:

  • (파일이나 문자열로부터 온) 완전한 파이썬 프로그램을 파싱할 때;

  • 모듈을 파싱할 때;

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