runpy
— Locating and executing Python modules¶
소스 코드: Lib/runpy.py
runpy
모듈은 파이썬 모듈을 먼저 임포트 하지 않고 찾아서 실행하는 데 사용합니다. 주요 용도는 파일 시스템이 아닌 파이썬 모듈 이름 공간을 사용하여 스크립트를 찾을 수 있는 -m
명령 줄 스위치를 구현하는 것입니다.
이것은 샌드박스 모듈이 아닙니다 - 모든 코드가 현재 프로세스에서 실행되고, 모든 부작용(가령 다른 모듈의 캐시된 임포트)은 함수가 반환된 후에도 그대로 유지됩니다.
또한, 실행된 코드에서 정의된 모든 함수와 클래스는 runpy
함수가 반환된 후 올바르게 작동하지 않을 수 있습니다. 이러한 제한이 주어진 사용 사례에 적합하지 않으면, 이 모듈보다 importlib
가 더 적합한 선택일 수 있습니다.
runpy
모듈은 두 가지 함수를 제공합니다:
- runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)¶
Execute the code of the specified module and return the resulting module globals dictionary. The module’s code is first located using the standard import mechanism (refer to PEP 302 for details) and then executed in a fresh module namespace.
mod_name 인자는 절대 모듈 이름이어야 합니다. 모듈 이름이 일반 모듈이 아닌 패키지를 참조하면, 해당 패키지를 임포트하고 그 패키지 내의
__main__
서브 모듈을 실행하고 결과 모듈 전역 딕셔너리를 반환합니다.The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by
run_module()
.The special global variables
__name__
,__spec__
,__file__
,__cached__
,__loader__
and__package__
are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail).__name__
은 (이 선택적 인자가None
이 아니면) run_name으로, 명명된 모듈이 패키지면mod_name + '.__main__'
으로, 그렇지 않으면 mod_name 인자로 설정됩니다.__spec__
will be set appropriately for the actually imported module (that is,__spec__.name
will always be mod_name ormod_name + '.__main__
, never run_name).__file__
,__cached__
,__loader__
및__package__
는 모듈 스펙에 따라 표준적으로 설정됩니다.인자 alter_sys가 제공되고
True
로 평가되면,sys.argv[0]
은__file__
값으로 갱신되고sys.modules[__name__]
은 실행 중인 모듈에 대한 임시 모듈 객체로 갱신됩니다.sys.argv[0]
과sys.modules[__name__]
은 함수가 반환되기 전에 원래 값으로 복원됩니다.이
sys
조작은 스레드-안전하지 않습니다. 다른 스레드가 부분적으로 초기화된 모듈과 변경된 인자 목록을 볼 수 있습니다. 스레드를 사용하는 코드에서 이 함수를 호출할 때sys
모듈을 단독으로 두는 것이 좋습니다.더 보기
명령 줄에서 동등한 기능을 제공하는
-m
옵션.버전 3.1에서 변경:
__main__
서브 모듈을 찾아 패키지를 실행할 수 있는 기능 추가.버전 3.2에서 변경:
__cached__
전역 변수 추가 (PEP 3147을 참조하십시오).버전 3.4에서 변경: PEP 451이 추가한 모듈 스펙 기능을 활용하도록 갱신되었습니다. 이것은 실제 모듈 이름을 항상
__spec__.name
으로 액세스할 수 있으면서,__cached__
가 이 방법으로 실행되는 모듈에 대해 올바르게 설정되도록 합니다.
- runpy.run_path(path_name, init_globals=None, run_name=None)¶
Execute the code at the named filesystem location and return the resulting module globals dictionary. As with a script name supplied to the CPython command line, the supplied path may refer to a Python source file, a compiled bytecode file or a valid
sys.path
entry containing a__main__
module (e.g. a zipfile containing a top-level__main__.py
file).간단한 스크립트의 경우, 지정된 코드는 단순히 새로운 모듈 이름 공간에서 실행됩니다. 유효한
sys.path
항목(보통 zip 파일이나 디렉터리)의 경우, 항목이 먼저sys.path
의 시작 부분에 추가됩니다. 그런 다음 함수는 갱신된 경로를 사용하여__main__
모듈을 찾아 실행합니다. 지정된 위치에 해당 모듈이 없을 때sys.path
의 다른 위치에 있는 기존__main__
항목을 호출하는 것을 막는 특별한 보호 장치가 없다는 점에 유의하십시오.The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by
run_path()
.The special global variables
__name__
,__spec__
,__file__
,__cached__
,__loader__
and__package__
are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail).__name__
은 (이 선택적 인자가None
이 아니면) run_name으로, 그렇지 않으면'<run_path>'
로 설정됩니다.If the supplied path directly references a script file (whether as source or as precompiled byte code), then
__file__
will be set to the supplied path, and__spec__
,__cached__
,__loader__
and__package__
will all be set toNone
.If the supplied path is a reference to a valid
sys.path
entry, then__spec__
will be set appropriately for the imported__main__
module (that is,__spec__.name
will always be__main__
).__file__
,__cached__
,__loader__
and__package__
will be set as normal based on the module spec.A number of alterations are also made to the
sys
module. Firstly,sys.path
may be altered as described above.sys.argv[0]
is updated with the value ofpath_name
andsys.modules[__name__]
is updated with a temporary module object for the module being executed. All modifications to items insys
are reverted before the function returns.run_module()
과 달리,sys
에 대한 변경은 이 함수에서는 선택 사항이 아닌데, 이 조정이sys.path
항목의 실행을 허용하는 데 필수적이기 때문입니다. 스레드-안전 제약 사항이 계속 적용되므로, 스레드를 사용하는 코드에서 이 함수를 사용하려면 임포트 잠금을 사용하여 직렬화하거나 별도의 프로세스에 위임해야 합니다.더 보기
명령 줄에서의 동등한 기능에 대한 인터페이스 옵션 (
python path/to/script
).버전 3.2에 추가.