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 or mod_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 to None.

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 of path_name and sys.modules[__name__] is updated with a temporary module object for the module being executed. All modifications to items in sys are reverted before the function returns.

run_module()과 달리, sys에 대한 변경은 이 함수에서는 선택 사항이 아닌데, 이 조정이 sys.path 항목의 실행을 허용하는 데 필수적이기 때문입니다. 스레드-안전 제약 사항이 계속 적용되므로, 스레드를 사용하는 코드에서 이 함수를 사용하려면 임포트 잠금을 사용하여 직렬화하거나 별도의 프로세스에 위임해야 합니다.

더 보기

명령 줄에서의 동등한 기능에 대한 인터페이스 옵션 (python path/to/script).

버전 3.2에 추가.

버전 3.4에서 변경: PEP 451이 추가한 모듈 스펙 기능을 활용하도록 갱신되었습니다. 이것은 __main__이 직접 실행되는 대신 유효한 sys.path 항목에서 임포트 될 때 __cached__가 올바르게 설정되도록 합니다.

더 보기

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

Nick Coghlan이 작성하고 구현한 PEP.

PEP 366 – 메인 모듈 명시적 상대 임포트

Nick Coghlan이 작성하고 구현한 PEP.

PEP 451 – 임포트 시스템의 ModuleSpec 형

Eric Snow가 작성하고 구현한 PEP

명령 줄과 환경 - CPython 명령 줄 세부 사항

importlib.import_module() 함수