1. 명령 줄과 환경

CPython 인터프리터는 명령 줄과 환경에서 다양한 설정을 찾습니다.

다른 구현의 명령 줄 체계는 다를 수 있습니다. 자세한 내용은 대안 구현들 참조하십시오.

1.1. 명령 줄

파이썬을 호출할 때 다음 옵션들을 지정할 수 있습니다:

python [-bBdEhiIOPqRsSuvVWx?] [-c command | -m module-name | script | - ] [args]

물론, 가장 일반적인 사용 사례는 간단한 스크립트 호출입니다:

python myscript.py

1.1.1. 인터페이스 옵션

인터프리터 인터페이스는 유닉스 셸의 인터페이스와 비슷하지만, 몇 가지 추가 호출 방법을 제공합니다:

  • tty 장치에 연결된 표준 입력으로 호출하면, 명령을 입력하라는 프롬프트를 준 후 EOF(파일 끝 문자, 유닉스에서는 Ctrl-D, 윈도우에서는 Ctrl-Z, Enter로 만들 수 있습니다)가 읽힐 때까지 실행합니다. 대화형 모드에 대한 자세한 내용은 대화형 모드를 참조하세요.

  • 파일 이름 인자나 파일을 표준 입력으로 사용해서 호출하면, 해당 파일에서 스크립트를 읽고 실행합니다.

  • 디렉터리 이름 인자로 호출되면, 해당 디렉터리에서 적절히 이름 붙은 스크립트를 읽고 실행합니다.

  • -c command 로 호출되면, command로 주어지는 파이썬 문장을 실행합니다. 여기서 command는 개행 문자로 구분된 여러 개의 문장을 포함할 수 있습니다. 선행 공백은 파이썬 문장에서 중요합니다!

  • -m module-name 으로 호출되면, 주어진 모듈을 파이썬 모듈 경로에서 찾은 후에 스크립트로 실행합니다.

비대화형 모드에서는, 실행하기 전에 전체 입력을 구문 분석합니다.

인터페이스 옵션은 인터프리터에 의해 소비되는 옵션의 목록을 종료합니다, 뒤따르는 모든 인자는 sys.argv 로 들어갑니다 – 첫 번째 요소, 서브 스크립트 0(sys.argv[0])은 프로그램 소스를 반영하는 문자열임에 유의하세요.

-c <command>

command 의 파이썬 코드를 실행합니다. command 는 개행 문자로 구분된 하나 이상의 문장일 수 있는데, 일반 모듈 코드에서와같이 선행 공백은 의미가 있습니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 "-c" 가 되고, 현재 디렉터리를 sys.path 의 시작 부분에 추가합니다 (그 디렉터리에 있는 모듈을 최상위 모듈로 임포트 할 수 있게 합니다).

command를 인자로 감사 이벤트(auditing event) cpython.run_command를 발생시킵니다.

버전 3.14에서 변경: command is automatically dedented before execution.

-m <module-name>

제공된 이름의 모듈을 sys.path 에서 검색하고 그 내용을 __main__ 모듈로서 실행합니다.

인자가 모듈 이름이기 때문에, 파일 확장자(.py)를 주지 않아야 합니다. 모듈 이름은 유효한 절대 파이썬 모듈 이름이어야 하지만, 구현이 항상 이를 강제하는 것은 아닙니다 (예를 들어, 하이픈을 포함하는 이름을 허락할 수도 있습니다).

패키지 이름(이름 공간 패키지 포함)도 허용됩니다. 일반 모듈 대신 패키지 이름이 제공되면, 인터프리터는 <pkg>.__main__ 을 메인 모듈로 실행합니다. 이 동작은 인터프리터에 스크립트 인자로 전달되는 디렉터리 및 zip 파일의 처리와 의도적으로 유사합니다.

참고

이 옵션은 내장 모듈이나 확장 모듈에는 사용될 수 없는데, 이것들은 파이썬 모듈 파일을 갖고 있지 않기 때문입니다. 그러나, 원래 소스 파일이 없는 사전 컴파일된 모듈에는 여전히 사용할 수 있습니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 모듈 파일의 전체 경로가 됩니다 (모듈 파일을 찾는 동안에는 첫 번째 요소를 "-m" 으로 설정합니다). -c 옵션과 마찬가지로, 현재 디렉터리가 sys.path 의 시작 부분에 추가됩니다.

-I 옵션을 사용하면 sys.path가 현재 디렉터리나 사용자의 site-packages 디렉터리를 포함하지 않는 격리 모드에서 스크립트를 실행할 수 있습니다. 모든 PYTHON* 환경 변수도 무시됩니다.

많은 표준 라이브러리 모듈에는 스크립트로 실행할 때 호출되는 코드가 들어 있습니다. 한 예는 timeit 모듈입니다:

python -m timeit -s "setup here" "benchmarked code here"
python -m timeit -h # for details

module-name을 인자로 감사 이벤트(auditing event) cpython.run_module을 발생시킵니다.

더 보기

runpy.run_module()

파이썬 코드에서 직접 사용할 수 있는 동등한 기능

PEP 338 – 모듈을 스크립트로 실행하기

버전 3.1에서 변경: __main__ 서브 모듈을 실행할 패키지 이름을 제공할 수 있습니다.

버전 3.4에서 변경: 이름 공간 패키지도 지원됩니다.

-

표준 입력(sys.stdin)에서 명령을 읽습니다. 표준 입력이 터미널이면, -i 가 묵시적으로 적용됩니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 "-" 이 되고, 현재 디렉터리가 sys.path 의 처음에 추가됩니다.

인자 없이 감사 이벤트(auditing event) cpython.run_stdin을 발생시킵니다.

<script>

script 에 담긴 파이썬 코드를 실행합니다. script 는 파이썬 파일이나 __main__.py 파일이 들어있는 디렉터리나 __main__.py 파일을 포함하는 zip 파일을 가리키는 파일 시스템 경로(절대나 상대)여야 합니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 명령 줄에서 주어진 스크립트 이름이 됩니다.

스크립트 이름이 파이썬 파일을 직접 가리키면, 해당 파일을 포함하는 디렉터리가 sys.path 의 시작 부분에 추가되고, 파일은 __main__ 모듈로 실행됩니다.

스크립트 이름이 디렉터리 나 zip 파일을 가리키면, 스크립트 이름이 sys.path 의 시작 부분에 추가되고, 해당 위치의 __main__.py 파일을 __main__ 모듈로 실행합니다.

-I 옵션을 사용하면 sys.path가 스크립트 디렉터리나 사용자의 site-packages 디렉터리를 포함하지 않는 격리 모드에서 스크립트를 실행할 수 있습니다. 모든 PYTHON* 환경 변수도 무시됩니다.

filename을 인자로 감사 이벤트(auditing event) cpython.run_file을 발생시킵니다.

더 보기

runpy.run_path()

파이썬 코드에서 직접 사용할 수 있는 동등한 기능

인터페이스 옵션을 주지 않으면, -i 가 묵시적으로 적용되고, sys.argv[0] 는 빈 문자열("")이 되고, 현재 디렉터리가 sys.path 의 처음에 추가됩니다. 또한, 플랫폼에서 사용 가능한 경우 (Readline 구성 를 참조하세요), 탭 완성 및 히스토리 편집이 자동으로 활성화됩니다.

버전 3.4에서 변경: 탭 완성과 히스토리 편집의 자동 활성화.

1.1.2. 일반 옵션

-?
-h
--help

모든 명령 줄 옵션과 해당 환경 변수에 대한 간단한 설명을 인쇄한 후 종료합니다.

--help-env

파이썬 특정 환경 변수에 대한 간단한 설명을 인쇄한 후 종료합니다.

Added in version 3.11.

--help-xoptions

Print a description of implementation-specific -X options and exit.

Added in version 3.11.

--help-all

Print complete usage information and exit.

Added in version 3.11.

-V
--version

파이썬 버전 번호를 출력하고 종료합니다. 출력 예는 다음과 같습니다:

Python 3.8.0b2+

두 번 지정하면, 다음과 같이 빌드에 관한 추가 정보를 인쇄합니다:

Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
[GCC 6.2.0 20161005]

Added in version 3.6: -VV 옵션.

1.1.3. 기타 옵션

-b

bytesbytearray를 인코딩을 지정하지 않고 str로 변환하거나, bytesbytearraystr과, bytesint와 비교할 때 경고를 합니다. 옵션이 두 번 주어지면 (-bb) 에러를 줍니다.

버전 3.5에서 변경: bytesint 비교에도 적용됩니다.

-B

주어지면, 파이썬은 소스 모듈을 임포트 할 때 .pyc 파일을 쓰려고 하지 않습니다. PYTHONDONTWRITEBYTECODE 도 참조하십시오.

--check-hash-based-pycs default|always|never

해시 기반 .pyc 파일의 검증 동작을 제어합니다. 캐시된 바이트 코드 무효화를 참조하세요. default 로 설정하면, 검사형과 비검사형 해시 기반 바이트 코드 캐시 파일은 기본 의미에 따라 유효성이 검사됩니다. always 로 설정하면, 모든 해시 기반 .pyc 파일들은, 검사형과 비검사형을 가리지 않고, 해당 소스 파일에 대해 유효성이 검사됩니다. never 로 설정되면, 해시 기반 .pyc 파일은 해당 소스 파일에 대해 유효성이 검사되지 않습니다.

타임스탬프 기반 .pyc 파일의 의미는 이 옵션의 영향을 받지 않습니다.

-d

파서 디버깅 출력을 켭니다 (전문가만을 위한 기능입니다). PYTHONDEBUG 환경 변수도 참조하십시오.

This option requires a debug build of Python, otherwise it’s ignored.

-E

설정되었을 수 있는 모든 PYTHON* 환경 변수를 무시합니다, 예를 들어 PYTHONPATHPYTHONHOME.

-P-I (격리) 옵션도 참조하십시오.

-i

Enter interactive mode after execution.

Using the -i option will enter interactive mode in any of the following circumstances:

  • 스크립트가 첫 번째 인자로 전달될 때

  • -c 옵션이 사용될 때

  • -m 옵션이 사용될 때

대화형 모드는 sys.stdin 가 터미널로 보이지 않을 때도 시작합니다. PYTHONSTARTUP 파일은 읽지 않습니다.

이것은 스크립트가 예외를 발생시킬 때 전역 변수나 스택 트레이스를 검사하는 데 유용할 수 있습니다. PYTHONINSPECT 도 참조하십시오.

-I

격리된 모드로 파이썬을 실행합니다. 이것은 또한 -E, -P-s 옵션을 묵시적으로 적용합니다.

격리 모드에서 sys.path 는 스크립트 디렉터리나 사용자의 site-packages 디렉터리를 포함하지 않습니다. 모든 PYTHON* 환경 변수도 무시됩니다. 사용자가 악성 코드를 주입하는 것을 방지하기 위해 추가 제한이 부과될 수 있습니다.

Added in version 3.4.

-O

assert 문과 __debug__ 의 값에 대한 조건부 코드를 제거합니다. .pyc 확장자 앞에 .opt-1 을 추가하여 컴파일된 (바이트 코드) 파일의 이름을 구분합니다 (PEP 488을 참조하세요). PYTHONOPTIMIZE 도 참조하십시오.

버전 3.5에서 변경: PEP 488 에 따라 .pyc 파일명을 수정합니다.

-OO

-O를 적용하고 독스트링도 버립니다. .pyc 확장자 앞에 .opt-2 를 추가하여 컴파일 된(바이트 코드) 파일의 이름을 구분합니다 (참조 PEP 488을 참조하세요).

버전 3.5에서 변경: PEP 488 에 따라 .pyc 파일명을 수정합니다.

-P

Don’t prepend a potentially unsafe path to sys.path:

  • python -m module command line: Don’t prepend the current working directory.

  • python script.py command line: Don’t prepend the script’s directory. If it’s a symbolic link, resolve symbolic links.

  • python -c code and python (REPL) command lines: Don’t prepend an empty string, which means the current working directory.

See also the PYTHONSAFEPATH environment variable, and -E and -I (isolated) options.

Added in version 3.11.

-q

대화형 모드에서도 저작권과 버전 메시지를 표시하지 않습니다.

Added in version 3.2.

-R

해시 무작위화를 켭니다. 이 옵션은 PYTHONHASHSEED 환경 변수가 0 으로 설정된 경우에만 효과가 있습니다, 해시 무작위화는 기본적으로 활성화되기 때문입니다.

이전 버전의 파이썬에서는, 이 옵션이 해시 무작위화를 켜서, str과 bytes 객체의 __hash__() 값이 예측할 수 없는 난수로 “솔트(salt)” 됩니다. 개별 파이썬 프로세스 내에서 상수로 유지되지만, 반복되는 파이썬 실행 간에는 예측할 수 없습니다.

해시 무작위화는 신중하게 선택된 입력으로 딕셔너리 구성의 최악의 경우 성능 O(n2) 복잡도를 공략하는 서비스 거부에 대한 보호를 제공하기 위한 것입니다. 자세한 내용은 http://ocert.org/advisories/ocert-2011-003.html 을 참조하십시오.

PYTHONHASHSEED 는 해시 시드 시크릿에 고정값을 설정할 수 있게 합니다.

Added in version 3.2.3.

버전 3.7에서 변경: 이 옵션은 더는 무시되지 않습니다.

-s

사용자 site-packages 디렉터리sys.path 에 추가하지 않습니다.

PYTHONNOUSERSITE 도 참조하세요.

더 보기

PEP 370 – 사용자별 site-packages 디렉터리

-S

site 모듈의 임포트와 이 모듈이 수반하는 sys.path 의 사이트 의존적 조작을 비활성화합니다. 또한 site 가 나중에 명시적으로 임포트될 때도 이 조작을 비활성화합니다 (조작하기를 원하면 site.main() 을 호출하십시오).

-u

stdout 과 stderr 스트림을 버퍼링하지 않도록 만듭니다. 이 옵션은 stdin 스트림에는 영향을 미치지 않습니다.

PYTHONUNBUFFERED 도 참조하세요.

버전 3.7에서 변경: stdout 과 stderr 스트림의 텍스트 계층은 이제 버퍼링 되지 않습니다.

-v

모듈이 초기화될 때마다 메시지를 인쇄하여, 로드된 위치(파일명이나 내장 모듈)를 표시합니다. 두 번 주어지면 (-vv), 모듈을 검색할 때 검사되는 각 파일에 대한 메시지를 인쇄합니다. 종료 시 모듈 정리에 대한 정보도 제공합니다.

버전 3.10에서 변경: The site module reports the site-specific paths and .pth files being processed.

PYTHONVERBOSE 도 참조하세요.

-W arg

경고 제어. 파이썬의 경고 장치는 기본적으로 sys.stderr 로 경고 메시지를 인쇄합니다.

가장 단순한 설정은 프로세스가 만드는 모든 경고에 무조건 특정 액션을 적용합니다 (그렇지 않으면 기본적으로 무시되는 경고조차도):

-Wdefault  # 호출 위치마다 한 번 경고합니다
-Werror    # 예외로 변환합니다
-Walways   # 매번 경고합니다
-Wall      # -Walways 와 같습니다
-Wmodule   # 호출하는 모듈마다 한 번 경고합니다
-Wonce     # 파이썬 프로세스마다 한 번 경고합니다
-Wignore   # 경고하지 않습니다

액션 이름은 원하면 줄일 수 있고, 인터프리터는 이를 적절한 액션 이름으로 해석합니다. 예를 들어, -Wi-Wignore와 같습니다.

The full form of argument is:

action:message:category:module:lineno

Empty fields match all values; trailing empty fields may be omitted. For example -W ignore::DeprecationWarning ignores all DeprecationWarning warnings.

The action field is as explained above but only applies to warnings that match the remaining fields.

The message field must match the whole warning message; this match is case-insensitive.

The category field matches the warning category (ex: DeprecationWarning). This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning category.

The module field matches the (fully qualified) module name; this match is case-sensitive.

The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.

다중 -W 옵션이 주어질 수 있습니다; 경고가 두 개 이상의 옵션과 일치하면 마지막으로 일치하는 옵션의 액션이 수행됩니다. 유효하지 않은 -W 옵션은 무시됩니다 (하지만, 최초의 경고가 발생할 때 유효하지 않은 옵션에 관한 경고 메시지가 출력됩니다).

경고는 PYTHONWARNINGS 환경 변수와 파이썬 프로그램 내에서 warnings 모듈을 사용해서 제어할 수도 있습니다. 예를 들어, warnings.filterwarnings() 함수는 경고 메시지에 정규식을 적용하는 데 사용할 수 있습니다.

자세한 내용은 경고 필터경고 필터 설명를 참조하십시오.

-x

소스의 첫 번째 줄을 건너 뛰어서, 유닉스 이외의 형식의 #!cmd 을 사용할 수 있게 합니다. 이것은 DOS 전용 핵(hack)을 위한 것입니다.

-X

다양한 구현 특정 옵션을 위해 예약되어 있습니다. CPython은 현재 다음과 같은 가능한 값을 정의합니다:

  • -X faulthandlerfaulthandler 를 활성화합니다. PYTHONFAULTHANDLER도 참조하세요.

    Added in version 3.3.

  • -X showrefcount 는 프로그램이 끝나거나 대화형 인터프리터에서 각각의 문장 뒤에서, 총 참조 횟수와 사용된 메모리 블록의 수를 출력합니다. 이것은 디버그 빌드에서만 작동합니다.

    Added in version 3.4.

  • -X tracemalloctracemalloc 모듈을 사용하여 파이썬 메모리 할당 추적을 시작합니다. 기본적으로, 가장 최근 프레임만 추적의 트레이스백에 저장됩니다. NFRAME 프레임의 트레이스백 한도로 추적을 시작하려면 -X tracemalloc=NFRAME 을 사용하십시오. 자세한 정보는 tracemalloc.start()PYTHONTRACEMALLOC을 참조하십시오.

    Added in version 3.4.

  • -X int_max_str_digits configures the integer string conversion length limitation. See also PYTHONINTMAXSTRDIGITS.

    Added in version 3.11.

  • -X importtime to show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python -X importtime -c 'import asyncio'.

    -X importtime=2 enables additional output that indicates when an imported module has already been loaded. In such cases, the string cached will be printed in both time columns.

    See also PYTHONPROFILEIMPORTTIME.

    Added in version 3.7.

    버전 3.14에서 변경: Added -X importtime=2 to also trace imports of loaded modules, and reserved values other than 1 and 2 for future use.

  • -X dev: 파이썬 개발 모드를 활성화해서, 기본적으로 활성화하기에는 너무 비싼 추가적인 실행시간 검사를 도입합니다. PYTHONDEVMODE도 참조하세요.

    Added in version 3.7.

  • -X utf8파이썬 UTF-8 모드를 활성화합니다. -X utf8=0 은 명시적으로 파이썬 UTF-8 모드를 비활성화합니다 (그렇지 않으면 자동으로 활성화될 때조차). PYTHONUTF8도 참조하십시오.

    Added in version 3.7.

  • -X pycache_prefix=PATH.pyc 파일을 코드 트리 대신에 지정된 디렉터리를 루트로 하는 병렬 트리에 쓰도록 합니다. PYTHONPYCACHEPREFIX도 참조하십시오.

    Added in version 3.8.

  • -X warn_default_encoding issues a EncodingWarning when the locale-specific default encoding is used for opening files. See also PYTHONWARNDEFAULTENCODING.

    Added in version 3.10.

  • -X no_debug_ranges disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks. See also PYTHONNODEBUGRANGES.

    Added in version 3.11.

  • -X frozen_modules determines whether or not frozen modules are ignored by the import machinery. A value of on means they get imported and off means they are ignored. The default is on if this is an installed Python (the normal case). If it’s under development (running from the source tree) then the default is off. Note that the importlib_bootstrap and importlib_bootstrap_external frozen modules are always used, even if this flag is set to off. See also PYTHON_FROZEN_MODULES.

    Added in version 3.11.

  • -X perf enables support for the Linux perf profiler. When this option is provided, the perf profiler will be able to report Python calls. This option is only available on some platforms and will do nothing if is not supported on the current system. The default value is “off”. See also PYTHONPERFSUPPORT and Python support for the Linux perf profiler.

    Added in version 3.12.

  • -X perf_jit enables support for the Linux perf profiler with DWARF support. When this option is provided, the perf profiler will be able to report Python calls using DWARF information. This option is only available on some platforms and will do nothing if is not supported on the current system. The default value is “off”. See also PYTHON_PERF_JIT_SUPPORT and Python support for the Linux perf profiler.

    Added in version 3.13.

  • -X disable_remote_debug disables the remote debugging support as described in PEP 768. This includes both the functionality to schedule code for execution in another process and the functionality to receive code for execution in the current process.

    This option is only available on some platforms and will do nothing if is not supported on the current system. See also PYTHON_DISABLE_REMOTE_DEBUG and PEP 768.

    Added in version 3.14.

  • -X cpu_count=n overrides os.cpu_count(), os.process_cpu_count(), and multiprocessing.cpu_count(). n must be greater than or equal to 1. This option may be useful for users who need to limit CPU resources of a container system. See also PYTHON_CPU_COUNT. If n is default, nothing is overridden.

    Added in version 3.13.

  • -X presite=package.module specifies a module that should be imported before the site module is executed and before the __main__ module exists. Therefore, the imported module isn’t __main__. This can be used to execute code early during Python initialization. Python needs to be built in debug mode for this option to exist. See also PYTHON_PRESITE.

    Added in version 3.13.

  • -X gil=0,1 forces the GIL to be disabled or enabled, respectively. Setting to 0 is only available in builds configured with --disable-gil. See also PYTHON_GIL and Free-threaded CPython.

    Added in version 3.13.

  • -X thread_inherit_context=0,1 causes Thread to, by default, use a copy of context of the caller of Thread.start() when starting. Otherwise, threads will start with an empty context. If unset, the value of this option defaults to 1 on free-threaded builds and to 0 otherwise. See also PYTHON_THREAD_INHERIT_CONTEXT.

    Added in version 3.14.

  • -X context_aware_warnings=0,1 causes the warnings.catch_warnings context manager to use a ContextVar to store warnings filter state. If unset, the value of this option defaults to 1 on free-threaded builds and to 0 otherwise. See also PYTHON_CONTEXT_AWARE_WARNINGS.

    Added in version 3.14.

  • -X tlbc=0,1 enables (1, the default) or disables (0) thread-local bytecode in builds configured with --disable-gil. When disabled, this also disables the specializing interpreter. See also PYTHON_TLBC.

    Added in version 3.14.

또한 sys._xoptions 딕셔너리를 통해 임의의 값을 전달하고 조회할 수 있도록 합니다.

Added in version 3.2.

버전 3.9에서 변경: -X showalloccount 옵션을 제거했습니다.

버전 3.10에서 변경: -X oldparser 옵션을 제거했습니다.

Removed in version 3.14: -J is no longer reserved for use by Jython, and now has no special meaning.

1.1.4. Controlling color

The Python interpreter is configured by default to use colors to highlight output in certain situations such as when displaying tracebacks. This behavior can be controlled by setting different environment variables.

Setting the environment variable TERM to dumb will disable color.

If the FORCE_COLOR environment variable is set, then color will be enabled regardless of the value of TERM. This is useful on CI systems which aren’t terminals but can still display ANSI escape sequences.

If the NO_COLOR environment variable is set, Python will disable all color in the output. This takes precedence over FORCE_COLOR.

All these environment variables are used also by other tools to control color output. To control the color output only in the Python interpreter, the PYTHON_COLORS environment variable can be used. This variable takes precedence over NO_COLOR, which in turn takes precedence over FORCE_COLOR.

1.2. 환경 변수

이 환경 변수들은 파이썬의 동작에 영향을 주며, -E와 -I 이외의 명령 줄 스위치보다 먼저 처리됩니다. 충돌하면 명령 줄 스위치가 환경 변수에 우선하는 것이 관례입니다.

PYTHONHOME

표준 파이썬 라이브러리의 위치를 변경합니다. 기본적으로, 라이브러리는 prefix/lib/pythonversionexec_prefix/lib/pythonversion에서 검색되는데, prefixexec_prefix 는 설치 의존적인 디렉터리이고, 둘 다 기본값은 /usr/local 입니다.

PYTHONHOME 이 하나의 디렉터리로 설정되면, 그 값은 prefixexec_prefix 를 모두 대체합니다. 이들에 대해 다른 값을 지정하려면, PYTHONHOMEprefix:exec_prefix 로 설정하십시오.

PYTHONPATH

모듈 파일의 기본 검색 경로를 보강합니다. 형식은 셸의 PATH 와 같습니다: 하나 이상의 디렉터리 경로명이 os.pathsep (예를 들어, 유닉스에서는 콜론, 윈도우에서는 세미콜론) 로 구분됩니다. 존재하지 않는 디렉터리는 조용히 무시됩니다.

일반 디렉터리 외에도, 개별 PYTHONPATH 엔트리는 순수 파이썬 모듈(소스 또는 컴파일된 형식)을 포함하는 zip 파일을 가리킬 수 있습니다. 확장 모듈은 zip 파일에서 임포트될 수 없습니다.

기본 검색 경로는 설치 의존적이지만, 일반적으로 prefix/lib/pythonversion으로 시작합니다 (위의 PYTHONHOME 을 참조하세요). 항상 PYTHONPATH 에 추가됩니다.

위에서 설명한 대로 인터페이스 옵션 하에서는 PYTHONPATH 앞에 검색 경로에 추가 디렉터리가 삽입됩니다. 검색 경로는 파이썬 프로그램 내에서 sys.path 변수로 조작할 수 있습니다.

PYTHONSAFEPATH

비어 있지 않은 문자열로 설정하면, 잠재적으로 안전하지 않은 경로를 sys.path 앞에 추가하지 않습니다: 자세한 내용은 -P 옵션을 참조하십시오.

Added in version 3.11.

PYTHONPLATLIBDIR

이것을 비어 있지 않은 문자열로 설정하면, sys.platlibdir 값을 재정의합니다.

Added in version 3.9.

PYTHONSTARTUP

이것이 읽을 수 있는 파일의 이름이면, 첫 번째 프롬프트가 대화형 모드에 표시되기 전에, 해당 파일의 파이썬 명령이 실행됩니다. 이 파일은 대화형 명령이 실행되는 것과 같은 이름 공간에서 실행되므로, 여기에서 정의되거나 임포트 한 객체를 대화형 세션에서 그대로 사용할 수 있습니다. 이 파일에서 프롬프트 sys.ps1sys.ps2 와 훅 sys.__interactivehook__ 도 바꿀 수 있습니다.

시작 시 호출될 때 filename을 인자로 감사 이벤트(auditing event) cpython.run_startup을 발생시킵니다.

PYTHONOPTIMIZE

비어 있지 않은 문자열로 설정하면 -O 옵션을 지정하는 것과 같습니다. 정수로 설정하면, -O를 여러 번 지정하는 것과 같습니다.

PYTHONBREAKPOINT

설정되면, 점으로 구분된 경로 표기법을 사용하여 콜러블의 이름을 지정합니다. 콜러블을 포함하는 모듈이 임포트 된 후에 콜러블은, 내장 breakpoint() 에 의해 호출되는 sys.breakpointhook() 의 기본 구현이 실행합니다. 설정되지 않았거나 빈 문자열로 설정하면, 값 “pdb.set_trace”와 동등합니다. 문자열 “0”으로 설정하면, sys.breakpointhook() 의 기본 구현은 아무것도 하지 않고 즉시 반환합니다.

Added in version 3.7.

PYTHONDEBUG

비어 있지 않은 문자열로 설정하면, -d 옵션을 지정하는 것과 같습니다. 정수로 설정하면, -d를 여러 번 지정하는 것과 같습니다.

This environment variable requires a debug build of Python, otherwise it’s ignored.

PYTHONINSPECT

비어 있지 않은 문자열로 설정하면, -i 옵션을 지정하는 것과 같습니다.

이 변수는 프로그램 종료 시 검사 모드를 강제하기 위해, os.environ 을 사용해서 파이썬 코드에 의해 수정될 수도 있습니다.

인자 없이 감사 이벤트(auditing event) cpython.run_stdin을 발생시킵니다.

버전 3.12.5에서 변경: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20) Emits audit events.

버전 3.13에서 변경: Uses PyREPL if possible, in which case PYTHONSTARTUP is also executed. Emits audit events.

PYTHONUNBUFFERED

비어 있지 않은 문자열로 설정하면, -u 옵션을 지정하는 것과 같습니다.

PYTHONVERBOSE

비어 있지 않은 문자열로 설정하면, -v 옵션을 지정하는 것과 같습니다. 정수로 설정하면 -v를 여러 번 지정하는 것과 같습니다.

PYTHONCASEOK

설정되면, 파이썬은 import 문에서 대소 문자를 무시합니다. 이것은 윈도우와 macOS에서만 작동합니다.

PYTHONDONTWRITEBYTECODE

비어 있지 않은 문자열로 설정되면, 파이썬은 소스 모듈을 임포트 할 때 .pyc 파일을 쓰지 않습니다. 이는 -B 옵션을 지정하는 것과 같습니다.

PYTHONPYCACHEPREFIX

설정되면, 파이썬은 소스 트리 내의 __pycache__ 디렉터리 대신에 이 경로에 있는 미러 디렉터리 트리에 .pyc 파일을 씁니다. 이것은 -X pycache_prefix=PATH 옵션을 지정하는 것과 동등합니다.

Added in version 3.8.

PYTHONHASHSEED

이 변수가 설정되어 있지 않거나 random 으로 설정되면, str과 bytes 객체의 해시 시드에 난수가 사용됩니다.

PYTHONHASHSEED 가 정숫값으로 설정되면, 해시 무작위화가 적용되는 형의 hash()를 생성하기 위한 고정 시드로 사용됩니다.

목적은 인터프리터 자체에 대한 셀프 테스트와 같은 이유로 반복 가능한 해싱을 허용하거나, 파이썬 프로세스 클러스터가 해시값을 공유하도록 허용하는 것입니다.

정수는 [0,4294967295] 범위의 십진수여야 합니다. 값 0을 지정하면 해시 무작위화가 비활성화됩니다.

Added in version 3.2.3.

PYTHONINTMAXSTRDIGITS

If this variable is set to an integer, it is used to configure the interpreter’s global integer string conversion length limitation.

Added in version 3.11.

PYTHONIOENCODING

인터프리터를 실행하기 전에 이것이 설정되면, stdin/stdout/stderr에 사용되는 인코딩을 대체합니다. 문법은 encodingname:errorhandler 형식입니다. encodingname:errorhandler 부분은 모두 선택 사항이며 str.encode() 에서와 같은 의미입니다.

stderr의 경우, :errorhandler 부분은 무시됩니다; 처리기는 항상 'backslashreplace' 입니다.

버전 3.4에서 변경: encodingname 부분은 이제 선택적입니다.

버전 3.6에서 변경: Windows에서, PYTHONLEGACYWINDOWSSTDIO 도 지정하지 않는 한, 대화형 콘솔 버퍼에서 이 변수로 지정된 인코딩이 무시됩니다. 표준 스트림을 통해 리디렉션 된 파일과 파이프는 영향을 받지 않습니다.

PYTHONNOUSERSITE

설정되면, 파이썬은 사용자 site-packages 디렉터리sys.path 에 추가하지 않습니다.

더 보기

PEP 370 – 사용자별 site-packages 디렉터리

PYTHONUSERBASE

사용자 베이스 디렉터리 를 정의합니다. 이 디렉터리는 python -m pip install --user 에서 사용자 site-packages 디렉터리 의 경로와 설치 경로 를 계산하는 데 사용됩니다.

더 보기

PEP 370 – 사용자별 site-packages 디렉터리

PYTHONEXECUTABLE

이 환경 변수가 설정되면, sys.argv[0] 는 C 런타임을 통해 얻은 값 대신에 이 값으로 설정됩니다. macOS에서만 작동합니다.

PYTHONWARNINGS

-W 옵션과 동등합니다. 쉼표로 구분된 문자열로 설정하면, -W를 여러 번 지정하는 것과 같습니다. 목록의 뒷부분에 있는 필터는 목록의 이전 필터보다 우선합니다.

가장 단순한 설정은 프로세스가 만드는 모든 경고에 무조건 특정 액션을 적용합니다 (그렇지 않으면 기본적으로 무시되는 경고조차도):

PYTHONWARNINGS=default  # 호출 위치마다 한 번 경고합니다
PYTHONWARNINGS=error    # 예외로 변환합니다
PYTHONWARNINGS=always   # 매번 경고합니다
PYTHONWARNINGS=all      # PYTHONWARNINGS=always 와 같습니다
PYTHONWARNINGS=module   # 호출하는 모듈마다 한 번 경고합니다
PYTHONWARNINGS=once     # 파이썬 프로세스마다 한 번 경고합니다
PYTHONWARNINGS=ignore   # 경고하지 않습니다

자세한 내용은 경고 필터경고 필터 설명를 참조하십시오.

PYTHONFAULTHANDLER

이 환경 변수가 비어 있지 않은 문자열로 설정되면, faulthandler.enable() 이 시작 시에 호출됩니다: 파이썬 트레이스백을 덤프하는 SIGSEGV, SIGFPE, SIGABRT, SIGBUS 그리고 SIGILL 시그널 처리기를 설치합니다. 이는 -X faulthandler 옵션과 동등합니다.

Added in version 3.3.

PYTHONTRACEMALLOC

이 환경 변수가 비어 있지 않은 문자열로 설정되면, tracemalloc 모듈을 사용하여 파이썬 메모리 할당 추적을 시작합니다. 변수의 값은 추적의 트레이스백에 저장되는 최대 프레임 수입니다. 예를 들어, PYTHONTRACEMALLOC=1 은 가장 최근의 프레임만을 저장합니다. 자세한 정보는 tracemalloc.start() 함수를 참조하십시오. 이는 -X tracemalloc 옵션을 설정하는 것과 동등합니다.

Added in version 3.4.

PYTHONPROFILEIMPORTTIME

If this environment variable is set to 1, Python will show how long each import takes. If set to 2, Python will include output for imported modules that have already been loaded. This is equivalent to setting the -X importtime option.

Added in version 3.7.

버전 3.14에서 변경: Added PYTHONPROFILEIMPORTTIME=2 to also trace imports of loaded modules.

PYTHONASYNCIODEBUG

이 환경 변수가 비어 있지 않은 문자열로 설정되면, asyncio 모듈의 디버그 모드 를 활성화합니다.

Added in version 3.4.

PYTHONMALLOC

파이썬 메모리 할당자를 설정하거나 디버그 훅을 설치합니다.

파이썬이 사용하는 메모리 할당자를 설정합니다:

Install debug hooks:

  • debug: 기본 메모리 할당자 위에 디버그 훅을 설치합니다.

  • malloc_debug: malloc 과 같지만, 디버그 훅도 설치합니다.

  • pymalloc_debug: pymalloc 과 같지만, 디버그 훅도 설치합니다.

  • mimalloc_debug: mimalloc 과 같지만, 디버그 훅도 설치합니다.

Added in version 3.6.

버전 3.7에서 변경: "default" 할당자를 추가했습니다.

PYTHONMALLOCSTATS

비어 있지 않은 문자열로 설정되면, 파이썬은 새로운 pymalloc 객체 영역이 생성될 때마다, 그리고 종료할 때 pymalloc 메모리 할당자 의 통계를 인쇄합니다.

PYTHONMALLOC 환경 변수를 사용하여 C 라이브러리의 malloc() 할당자를 강제로 사용하거나, pymalloc 지원 없이 파이썬을 구성하면, 이 변수는 무시됩니다.

버전 3.6에서 변경: 이 변수는 이제 배포 모드로 컴파일된 파이썬에서도 사용할 수 있습니다. 이제 빈 문자열로 설정하면 효과가 없습니다.

PYTHONLEGACYWINDOWSFSENCODING

비어 있지 않은 문자열로 설정하면, 기본 파일 시스템 인코딩과 에러 처리기 모드를 3.6 이전의 값인 ‘mbcs’와 ‘replace’로 각각 되돌립니다. 그렇지 않으면, 새 기본값 ‘utf-8’과 ‘surrogatepass’가 사용됩니다.

이것은 또한 실행 시간에 sys._enablelegacywindowsfsencoding() 으로 활성화 될 수 있습니다.

가용성: Windows.

Added in version 3.6: 자세한 내용은 PEP 529를 참조하십시오.

PYTHONLEGACYWINDOWSSTDIO

비어 있지 않은 문자열로 설정하면, 새 콘솔 입력기와 출력기를 사용하지 않습니다. 이것은 유니코드 문자가 utf-8을 사용하는 대신 활성 콘솔 코드 페이지에 따라 인코딩됨을 의미합니다.

이 변수는 표준 스트림이 콘솔 버퍼를 참조하는 대신 리디렉트 된 (파일 또는 파이프로) 경우 무시됩니다.

가용성: Windows.

Added in version 3.6.

PYTHONCOERCECLOCALE

0 으로 설정하면, 주 파이썬 명령 줄 응용 프로그램이 레거시 ASCII 기반 C와 POSIX 로케일을 보다 유능한 UTF-8 기반 대안으로 강제 변환하지 않습니다.

이 변수가 설정되지 않고 (또는 0 이외의 값으로 설정되고), 환경 변수에 우선하는 LC_ALL 로케일도 설정되지 않고, LC_CTYPE 범주에 대해 보고되는 현재 로케일이 기본 C 로케일이거나 명시적인 ASCII 기반의 POSIX 로케일이면, 파이썬 CLI는 인터프리터 런타임을 로드하기 전에 LC_CTYPE 범주에 대해 다음 로케일을 나열된 순서대로 구성하려고 시도합니다:

  • C.UTF-8

  • C.utf8

  • UTF-8

이러한 로케일 범주 중 하나를 설정하는 데 성공하면, 파이썬 런타임이 초기화되기 전에 LC_CTYPE 환경 변수도 현재 프로세스 환경에서 적절히 설정됩니다. 이렇게 하면 인터프리터 자신과 같은 프로세스에서 실행되는 다른 로케일 인식 구성 요소(가령 GNU readline 라이브러리)가 볼 수 있는 것에 더해, 갱신된 설정을 현재 C 로케일이 아닌 환경을 조회하는 연산(가령 파이썬 자체의 locale.getdefaultlocale())뿐만 아니라, 자식 프로세스에서도 (이 프로세스가 파이썬 인터프리터를 실행하는지에 관계없이) 볼 수 있습니다.

이러한 로케일 중 하나를 구성하면 (명시적으로나 위의 묵시적 로케일 강제 변경을 통해) sys.stdinsys.stdout 에 대해 surrogateescape 에러 처리기 를 자동으로 활성화합니다 (sys.stderr 는 다른 로케일에서처럼 backslashreplace 를 계속 사용합니다). 이 스트림 처리 동작은 평소처럼 PYTHONIOENCODING을 사용하여 대체할 수 있습니다.

디버깅을 위해, PYTHONCOERCECLOCALE=warn 을 설정하면, 로케일 강제 변경이 일어나거나, 그렇지 않고 강제 변경을 유발할 로케일이 파이썬 런타임이 초기화될 때 여전히 활성 상태면 파이썬은 stderr 로 경고 메시지를 보냅니다.

또한, 로케일 강제 변환이 비활성화되거나 적절한 대상 로케일을 찾지 못할 때도, 레거시 ASCII 기반 로케일에서 PYTHONUTF8 은 기본적으로 활성화됨에 유의하십시오. 인터프리터가 시스템 인터페이스에 대해 UTF-8 대신에 ASCII 를 사용하게 하려면, 두 가지 기능을 모두 비활성화시켜야 합니다.

가용성: Unix.

Added in version 3.7: 자세한 내용은 PEP 538을 참조하십시오.

PYTHONDEVMODE

이 환경 변수가 비어 있지 않은 문자열로 설정되면, 파이썬 개발 모드를 활성화하여, 기본적으로 활성화하기에는 너무 비싼 추가 실행 시간 검사를 도입합니다. 이는 -X dev 옵션을 설정하는 것과 동등합니다.

Added in version 3.7.

PYTHONUTF8

If set to 1, enable the Python UTF-8 Mode.

If set to 0, disable the Python UTF-8 Mode.

다른 모든 비어 있지 않은 문자열로 설정하면, 인터프리터를 초기화하는 동안 에러가 발생합니다.

Added in version 3.7.

PYTHONWARNDEFAULTENCODING

If this environment variable is set to a non-empty string, issue a EncodingWarning when the locale-specific default encoding is used.

See Opt-in EncodingWarning for details.

Added in version 3.10.

PYTHONNODEBUGRANGES

If this variable is set, it disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks.

Added in version 3.11.

PYTHONPERFSUPPORT

If this variable is set to a nonzero value, it enables support for the Linux perf profiler so Python calls can be detected by it.

If set to 0, disable Linux perf profiler support.

-X perf 명령줄 옵션과 Python support for the Linux perf profiler도 참조하십시오.

Added in version 3.12.

PYTHON_PERF_JIT_SUPPORT

If this variable is set to a nonzero value, it enables support for the Linux perf profiler so Python calls can be detected by it using DWARF information.

If set to 0, disable Linux perf profiler support.

-X perf_jit 명령줄 옵션과 Python support for the Linux perf profiler도 참조하십시오.

Added in version 3.13.

PYTHON_DISABLE_REMOTE_DEBUG

If this variable is set to a non-empty string, it disables the remote debugging feature described in PEP 768. This includes both the functionality to schedule code for execution in another process and the functionality to receive code for execution in the current process.

See also the -X disable_remote_debug command-line option.

Added in version 3.14.

PYTHON_CPU_COUNT

If this variable is set to a positive integer, it overrides the return values of os.cpu_count() and os.process_cpu_count().

-X cpu_count 명령줄 옵션도 참조하십시오.

Added in version 3.13.

PYTHON_FROZEN_MODULES

If this variable is set to on or off, it determines whether or not frozen modules are ignored by the import machinery. A value of on means they get imported and off means they are ignored. The default is on for non-debug builds (the normal case) and off for debug builds. Note that the importlib_bootstrap and importlib_bootstrap_external frozen modules are always used, even if this flag is set to off.

-X frozen_modules 명령줄 옵션도 참조하십시오.

Added in version 3.13.

PYTHON_COLORS

If this variable is set to 1, the interpreter will colorize various kinds of output. Setting it to 0 deactivates this behavior. See also Controlling color.

Added in version 3.13.

PYTHON_BASIC_REPL

If this variable is set to any value, the interpreter will not attempt to load the Python-based REPL that requires curses and readline, and will instead use the traditional parser-based REPL.

Added in version 3.13.

PYTHON_HISTORY

This environment variable can be used to set the location of a .python_history file (by default, it is .python_history in the user’s home directory).

Added in version 3.13.

PYTHON_GIL

If this variable is set to 1, the global interpreter lock (GIL) will be forced on. Setting it to 0 forces the GIL off (needs Python configured with the --disable-gil build option).

See also the -X gil command-line option, which takes precedence over this variable, and Free-threaded CPython.

Added in version 3.13.

PYTHON_THREAD_INHERIT_CONTEXT

If this variable is set to 1 then Thread will, by default, use a copy of context of the caller of Thread.start() when starting. Otherwise, new threads will start with an empty context. If unset, this variable defaults to 1 on free-threaded builds and to 0 otherwise. See also -X thread_inherit_context.

Added in version 3.14.

PYTHON_CONTEXT_AWARE_WARNINGS

If set to 1 then the warnings.catch_warnings context manager will use a ContextVar to store warnings filter state. If unset, this variable defaults to 1 on free-threaded builds and to 0 otherwise. See -X context_aware_warnings.

Added in version 3.14.

PYTHON_JIT

On builds where experimental just-in-time compilation is available, this variable can force the JIT to be disabled (0) or enabled (1) at interpreter startup.

Added in version 3.13.

PYTHON_TLBC

If set to 1 enables thread-local bytecode. If set to 0 thread-local bytecode and the specializing interpreter are disabled. Only applies to builds configured with --disable-gil.

See also the -X tlbc command-line option.

Added in version 3.14.

1.2.1. 디버그 모드 변수

PYTHONDUMPREFS

설정되면, 파이썬은 인터프리터를 종료한 후에도 살아있는 객체와 참조 횟수를 덤프합니다.

파이썬이 --with-trace-refs 빌드 옵션으로 구성되었어야 합니다.

PYTHONDUMPREFSFILE

설정되면, 파이썬은 인터프리터를 종료한 후에도 살아있는 객체와 참조 횟수를 이 환경 변수의 값으로 주어진 경로에 파일로 덤프합니다.

파이썬이 --with-trace-refs 빌드 옵션으로 구성되었어야 합니다.

Added in version 3.11.

PYTHON_PRESITE

If this variable is set to a module, that module will be imported early in the interpreter lifecycle, before the site module is executed, and before the __main__ module is created. Therefore, the imported module is not treated as __main__.

This can be used to execute code early during Python initialization.

To import a submodule, use package.module as the value, like in an import statement.

See also the -X presite command-line option, which takes precedence over this variable.

파이썬이 --with-pydebug 빌드 옵션으로 구성되었어야 합니다.

Added in version 3.13.