runpy — 파이썬 모듈 찾기와 실행

소스 코드: Lib/runpy.py


runpy 모듈은 파이썬 모듈을 먼저 임포트 하지 않고 찾아서 실행하는 데 사용합니다. 주요 용도는 파일 시스템이 아닌 파이썬 모듈 이름 공간을 사용하여 스크립트를 찾을 수 있는 -m 명령 줄 스위치를 구현하는 것입니다.

이것은 샌드박스 모듈이 아닙니다 - 모든 코드가 현재 프로세스에서 실행되고, 모든 부작용(가령 다른 모듈의 캐시된 임포트)은 함수가 반환된 후에도 그대로 유지됩니다.

또한, 실행된 코드에서 정의된 모든 함수와 클래스는 runpy 함수가 반환된 후 올바르게 작동하지 않을 수 있습니다. 이러한 제한이 주어진 사용 사례에 적합하지 않으면, 이 모듈보다 importlib가 더 적합한 선택일 수 있습니다.

runpy 모듈은 두 가지 함수를 제공합니다:

runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)

지정된 모듈의 코드를 실행하고 결과 모듈 전역 딕셔너리를 반환합니다. 모듈의 코드는 먼저 표준 임포트 메커니즘(자세한 내용은 PEP 302를 참조하십시오)을 사용하여 찾은 다음 새로운 모듈 이름 공간에서 실행됩니다.

The mod_name argument should be an absolute module name. If the module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned.

선택적 딕셔너리 인자 init_globals는 코드가 실행되기 전에 모듈의 전역 딕셔너리를 미리 채우기 위해 사용될 수 있습니다. 제공된 딕셔너리는 수정되지 않습니다. 아래의 특수 전역 변수가 제공된 딕셔너리에 정의되어 있으면, 해당 정의가 run_module()에 의해 대체됩니다.

특수 전역 변수 __name__, __spec__, __file__, __cached__, __loader____package__는 모듈 코드가 실행되기 전에 전역 딕셔너리에 설정됩니다 (이 변수는 최소한의 변수 집합임에 유의하십시오 - 인터프리터 구현 세부 사항에 따라 다른 변수가 묵시적으로 설정될 수 있습니다).

__name__은 (이 선택적 인자가 None이 아니면) run_name으로, 명명된 모듈이 패키지면 mod_name + '.__main__'으로, 그렇지 않으면 mod_name 인자로 설정됩니다.

__spec__실제로 임포트 된 모듈에 맞게 설정됩니다 (즉, __spec__.name은 항상 mod_name이나 mod_name + '.__main__이 됩니다, 절대 run_name은 아닙니다).

__file__, __cached__, __loader____package__는 모듈 스펙에 따라 표준적으로 설정됩니다.

인자 alter_sys가 제공되고 True로 평가되면, sys.argv[0]__file__ 값으로 갱신되고 sys.modules[__name__]은 실행 중인 모듈에 대한 임시 모듈 객체로 갱신됩니다. sys.argv[0]sys.modules[__name__]은 함수가 반환되기 전에 원래 값으로 복원됩니다.

Note that this manipulation of sys is not thread-safe. Other threads may see the partially initialised module, as well as the altered list of arguments. It is recommended that the sys module be left alone when invoking this function from threaded code.

더 보기

명령 줄에서 동등한 기능을 제공하는 -m 옵션.

버전 3.1에서 변경: Added ability to execute packages by looking for a __main__ submodule.

버전 3.2에서 변경: __cached__ 전역 변수 추가 (PEP 3147을 참조하십시오).

버전 3.4에서 변경: PEP 451이 추가한 모듈 스펙 기능을 활용하도록 갱신되었습니다. 이것은 실제 모듈 이름을 항상 __spec__.name으로 액세스할 수 있으면서, __cached__가 이 방법으로 실행되는 모듈에 대해 올바르게 설정되도록 합니다.

버전 3.12에서 변경: The setting of __cached__, __loader__, and __package__ are deprecated. See ModuleSpec for alternatives.

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).

For a simple script, the specified code is simply executed in a fresh module namespace. For a valid sys.path entry (typically a zipfile or directory), the entry is first added to the beginning of sys.path. The function then looks for and executes a __main__ module using the updated path. Note that there is no special protection against invoking an existing __main__ entry located elsewhere on sys.path if there is no such module at the specified location.

선택적 딕셔너리 인자 init_globals는 코드가 실행되기 전에 모듈의 전역 딕셔너리를 미리 채우기 위해 사용될 수 있습니다. 제공된 딕셔너리는 수정되지 않습니다. 아래의 특수 전역 변수가 제공된 딕셔너리에 정의되어 있으면, 해당 정의가 run_path()에 의해 대체됩니다.

특수 전역 변수 __name__, __spec__, __file__, __cached__, __loader____package__는 모듈 코드가 실행되기 전에 전역 딕셔너리에 설정됩니다 (이 변수는 최소한의 변수 집합임에 유의하십시오 - 인터프리터 구현 세부 사항에 따라 다른 변수가 묵시적으로 설정될 수 있습니다).

__name__은 (이 선택적 인자가 None이 아니면) run_name으로, 그렇지 않으면 '<run_path>'로 설정됩니다.

제공된 경로가 스크립트 파일(소스나 사전 컴파일된 바이트 코드)을 직접 참조하면, __file__은 제공된 경로로 설정되고 __spec__, __cached__, __loader____package__는 모두 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.

Note that, unlike run_module(), the alterations made to sys are not optional in this function as these adjustments are essential to allowing the execution of sys.path entries. As the thread-safety limitations still apply, use of this function in threaded code should be either serialised with the import lock or delegated to a separate process.

더 보기

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

버전 3.2에 추가.

버전 3.4에서 변경: Updated to take advantage of the module spec feature added by PEP 451. This allows __cached__ to be set correctly in the case where __main__ is imported from a valid sys.path entry rather than being executed directly.

버전 3.12에서 변경: The setting of __cached__, __loader__, and __package__ are deprecated.

더 보기

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

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

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

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

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

Eric Snow가 작성하고 구현한 PEP

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

importlib.import_module() 함수