파이썬 옵션, 파이썬 -m 옵션, python -m option, -u 옵션, 명령행 옵션, -c 옵션
파이썬 실행시 옵션에 대해 알아보겠습니다.

파이썬 실행 옵션(설명)
python을 커맨드창에서 실행할때, 아래와 같이 실행하면 됩니다.
python [옵션] argument
python에서는 아래와 같은 옵션들을 제공합니다.
-b: bytes 나 bytearray 를 str과, bytes를 int와 비교할 때 경고를 내보냅니다.
-bb: bytes 나 bytearray 를 str과, bytes를 int와 비교할 때 에러를 내보냅니다.
-B: Import 시 .pyc 파일을 쓰지 않습니다.
-c : 의 파이썬 코드를 실행합니다.
-d : 파서 디버깅 출력 켜기
-E: PYTHON* 환경변수 무시 (PYTHONPATH 등)
-h: 도움말 메시지를 출력 (-help 옵션과 동일)
-i: 스크립트 실행 후 대화형 모드로 진입
-I: Python을 사용자의 환경으로부터 격리
-m : 라이브러리 모듈을 스크립트로 실행
-O: assert 및 debug 조건문 코드를 제거합니다.
.pyc 확장자 앞에 .opt-1을 추가하여 컴파일된 파일의 이름을 구분합니다.
-OO: -O 옵션을 적용하고, docstring을 버립니다.
.pyc 확장자 앞에 .opt-2 추가하여 컴파일된 파일의 이름을 구분합니다.
-q: 대화형 모드에서 버전 및 저작권 메시지를 인쇄하지 않음
-s: site-package 디렉터리를 sys.path에 추가하지 않습니다.
-S: 초기화 시 ‘import site’를 하지 않습니다.
-u: stdout 스트림과 stderr 스트림을 버퍼하지 않도록 합니다.
-v: verbose 옵션 활성화
-V: Python 버전 번호 출력
-W : arg 는 action:message:category:module:lineno 형태로 쓰여집니다.
빈 필드는 모든 값이 매칭이 됩니다. 예를 들어, -W ignore::DeprecationWarning 은 모든 DeprecationWarning 경고를 무시합니다.
-x : 첫 번째 소스 라인을 건너뛰어 #!cmd의 비유닉스 형식을 사용할 수 있습니다.
-X : 특정한 옵션을 사용할 수 있습니다. -X와 opt를 결합한 옵션은 다음과 같은것들이 있습니다.
-X faulthandler: faulthandler 활성화
-X showrefcount : 총 reference count 및 사용 횟수 출력
프로그램이 종료되거나 각 문장이 끝난 후 메모리가 차단됩니다.
디버그 빌드에서만 작동합니다.
-X tracemalloc: Python 메모리 할당 추적 시작
Tracemalloc 모듈입니다. 기본적으로 가장 최근의 프레임만 a에 저장됩니다.
-X importtime: 각 imprt가 얼마나 걸리는지 표시합니다. 모듈 이름을 표시합니다.
누적 시간 (중첩 수입 포함) 및 자체 시간 출력. 멀티 스레드에서 출력이 깨질 수 있습니다.
응용 프로그램. 사용 예는 python3 -X importtime -c ‘import asyncio’ 입니다.
-X dev : CPython의 “개발 모드” 활성화, 추가 런타임 도입
개발 모드:
- -W default로 default warning filter 추가
- 메모리 할당기에 debug hook 설치: PyMem_SetupDebugHooks () C 기능 참조
- Faulthandler 모듈이 Python Traceback을 crash에 dump하도록 설정
- Asyncio debug 모드 사용
- sys.flags의 dev_mode 속성을 True로 설정
- io.IOBase 파괴자 로그 닫기 ( ) 예외
-X utf8: 운영 체제 인터페이스에 UTF-8 모드를 활성화합니다.
-X pycache_prefix=PATH: .pyc 파일을 코드 트리 대신에 지정된 디렉터리를 루트로 하는 병렬 트리에 쓰도록 합니다.
-X warn_default_encoding: ‘encoding=None’에 대한 opt-in EncodingWarning을 활성화
주요 옵션 실행예제
몇가지 옵션을 넣어 실행한 예제들을 살펴보겠습니다.
참고로 test.py 파일 내용은 아래와 같이 작성하였습니다.
1 | //test.py 파일 내용 |
python을 옵션 넣어서 실행해본 결과
1 | C:\>python -c print('test') |
파이썬 실행 옵션(원문)
usage: python [option] … [-c cmd | -m mod | file | -] [arg] …
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don’t write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also –help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user’s environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and debug-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-q : don’t print version and copyright messages on interactive startup
-s : don’t add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don’t imply ‘import site’ on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also –version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X showrefcount: output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on debug builds
-X tracemalloc: start tracing Python memory allocations using the
tracemalloc module. By default, only the most recent frame is stored in a
traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a
traceback limit of NFRAME frames
-X importtime: 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 python3 -X importtime -c ‘import asyncio’
-X dev: enable CPython’s “development mode”, introducing additional runtime
checks which are too expensive to be enabled by default. Effect of the
developer mode:
- Add default warning filter, as -W default
- Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function
- Enable the faulthandler module to dump the Python traceback on a crash
- Enable asyncio debug mode
- Set the dev_mode attribute of sys.flags to True
- io.IOBase destructor logs close() exceptions
-X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
otherwise activate automatically)
-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
given directory instead of to the code tree
-X warn_default_encoding: enable opt-in EncodingWarning for ‘encoding=None’
총평
보통 python [파일이름] 으로 파이썬 스크립트를 실행하고 따로 옵션을 사용하지 않는데,
파이썬 실행시 이렇게 다양한 옵션이 있을줄은 몰랐네요.
그렇지만 옵션 하나하나 보았을때, 역시나 쓸일이 거의 없을거 같긴합니다.
요즘에는 IDE도 잘 만들어져 있고, ipython notebook 같은 util 프로그램을 통해서 파이썬 코드를 작성하고,
바로 실행및 결과가 바로 출력이 되니 옵션을 굳이 몰라도 되지 않을까 싶긴 합니다.
#파이썬, #옵션, #파이썬옵션, #명령행, #명령행옵션, #option, #python, #-m, #-u, #-moption, #-uoption