16. 부록

16.1. 대화형 모드

16.1.1. 에러 처리

When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit status; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output.

기본 또는 보조 프롬프트에 인터럽트 문자 (일반적으로 Control-C 또는 Delete)를 입력하면 입력을 취소하고 기본 프롬프트로 돌아갑니다. [1] 명령어가 실행되는 동안 인터럽트를 입력하면 try 문에 의해 처리될 수 있는 KeyboardInterrupt 예외가 발생합니다.

16.1.2. 실행 가능한 파이썬 스크립트

BSD 스타일의 유닉스 시스템에서 파이썬 스크립트는 셸 스크립트처럼 직접 실행할 수 있게 만들 수 있습니다. 다음과 같은 줄

#!/usr/bin/env python3.5

(인터프리터가 사용자의 PATH 에 있다고 가정할 때)을 스크립트의 시작 부분에 넣고 파일에 실행 가능 모드를 줍니다. #! 는 반드시 파일의 처음 두 문자여야 합니다. 일부 플랫폼에서는 이 첫 번째 줄이 유닉스 스타일의 줄 종료 ('\n')로 끝나야 하며, 윈도우 줄 종료('\r\n')는 허락되지 않습니다. 파이썬에서 해시, 또는 파운드, 문자 '#' 는 주석을 시작하는 데 사용됩니다.

스크립트는 chmod 명령을 사용하여 실행 가능한 모드, 또는 권한, 을 부여받을 수 있습니다.

$ chmod +x myscript.py

윈도우 시스템에서는 “실행 가능 모드”라는 개념이 없습니다. 파이썬 설치 프로그램은 .py 파일을 python.exe와 자동으로 연결하여, 파이썬 파일을 이중 클릭하면 스크립트로 실행합니다. 확장자는 .pyw 일 수도 있습니다. 이 경우, 일반적으로 나타나는 콘솔 창은 표시되지 않습니다.

16.1.3. 대화형 시작 파일

파이썬을 대화형으로 사용할 때, 종종 인터프리터가 시작될 때마다 실행되는 표준 명령들이 있으면 편리합니다. PYTHONSTARTUP 환경 변수를 시작 명령이 들어있는 파일 이름으로 설정하면 됩니다. 이것은 유닉스 셸의 .profile 기능과 유사합니다.

이 파일은 대화형 세션에서만 읽히며, 파이썬이 스크립트에서 명령을 읽을 때나, /dev/tty 가 명령의 명시적 소스인 경우(대화형 세션처럼 동작한다)에는 읽지 않습니다. 대화형 명령이 실행되는 같은 이름 공간에서 실행되므로, 이 파일에서 정의하거나 임포트하는 객체들을 대화형 세션에서 정규화하지 않은 이름으로 사용할 수 있습니다. 이 파일에서 sys.ps1sys.ps2 프롬프트를 변경할 수도 있습니다.

현재 디렉터리에서 추가 시작 파일을 읽으려면, 전역 시작 파일에서 if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read()) 와 같은 코드를 사용해서 프로그램할 수 있습니다. 스크립트에서 시작 파일을 사용하려면 스크립트에서 명시적으로 수행해야 합니다:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)

16.1.4. 커스터마이제이션 모듈

Python provides two hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.5/site-packages'

이제 그 디렉터리에 usercustomize.py 라는 이름의 파일을 만들고 원하는 것들을 넣을 수 있습니다. 자동 임포트를 비활성화하는 -s 옵션으로 시작하지 않는 한, 이 파일은 모든 파이썬 실행에 영향을 줍니다.

sitecustomize works in the same way, but is typically created by an administrator of the computer in the global site-packages directory, and is imported before usercustomize. See the documentation of the site module for more details.

각주