모듈 임포트 하기

PyObject *PyImport_ImportModule(const char *name)
Return value: New reference. Part of the Stable ABI.

This is a wrapper around PyImport_Import() which takes a const char* as an argument instead of a PyObject*.

PyObject *PyImport_ImportModuleNoBlock(const char *name)
Return value: New reference. Part of the Stable ABI.

이 함수는 PyImport_ImportModule()의 폐지된 별칭입니다.

버전 3.3에서 변경: 이 기능은 다른 스레드가 임포트 잠금을 보유한 경우 즉시 실패했었습니다. 그러나 파이썬 3.3에서는, 잠금 방식이 대부분의 목적에서 모듈 단위 잠금으로 전환되었기 때문에, 이 함수의 특수한 동작은 더는 필요하지 않습니다.

PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)
Return value: New reference.

모듈을 임포트 합니다. 내장 파이썬 함수 __import__()를 통해 가장 잘 설명할 수 있습니다.

반환 값은 임포트 된 모듈이나 최상위 패키지에 대한 새로운 참조, 또는 실패 시 예외가 설정된 NULL입니다. __import__()와 마찬가지로, 비어 있지 않은 fromlist가 제공되지 않는 한, 패키지의 서브 모듈이 요청되었을 때의 반환 값은 최상위 패키지입니다.

임포트 실패는 PyImport_ImportModule()처럼 불완전한 모듈 객체를 제거합니다.

PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI since version 3.7.

모듈을 임포트 합니다. 표준 __import__() 함수가 이 함수를 직접 호출하기 때문에, 내장 파이썬 함수 __import__()를 통해 가장 잘 설명할 수 있습니다.

반환 값은 임포트 된 모듈이나 최상위 패키지에 대한 새로운 참조, 또는 실패 시 예외가 설정된 NULL입니다. __import__()와 마찬가지로, 비어 있지 않은 fromlist가 제공되지 않는 한, 패키지의 서브 모듈이 요청되었을 때의 반환 값은 최상위 패키지입니다.

버전 3.3에 추가.

PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI.

PyImport_ImportModuleLevelObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

버전 3.3에서 변경: level의 음수 값은 더는 허용되지 않습니다.

PyObject *PyImport_Import(PyObject *name)
Return value: New reference. Part of the Stable ABI.

이것은 현재 “임포트 훅 함수”를 호출하는 고수준 인터페이스입니다 (명시적인 level 0을 사용하는데, 절대 임포트를 뜻합니다). 현재 전역의 __builtins__에 있는 __import__() 함수를 호출합니다. 이는 현재 환경에 설치된 임포트 훅을 사용하여 임포트가 수행됨을 의미합니다.

이 함수는 항상 절대 임포트를 사용합니다.

PyObject *PyImport_ReloadModule(PyObject *m)
Return value: New reference. Part of the Stable ABI.

모듈을 다시 로드(reload)합니다. 다시 로드된 모듈에 대한 참조를 반환하거나, 실패 시 예외가 설정된 NULL을 반환합니다 (이때 모듈은 여전히 존재합니다).

PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7.

모듈 이름에 해당하는 모듈 객체를 반환합니다. name 인자는 package.module 형식일 수 있습니다. 먼저 모듈 딕셔너리에 있는지 확인하고, 없으면 새로 만들어 모듈 딕셔너리에 삽입합니다. 실패 시 예외를 설정하고 NULL을 반환합니다.

참고

이 함수는 모듈을 로드하거나 임포트 하지 않습니다; 모듈이 아직 로드되지 않았으면, 빈 모듈 객체를 얻게 됩니다. 모듈을 임포트 하려면 PyImport_ImportModule()이나 그 변형 중 하나를 사용하십시오. name에서 점으로 구분된 이름으로 암시된 패키지 구조는 이미 존재하지 않는다면 만들어지지 않습니다.

버전 3.3에 추가.

PyObject *PyImport_AddModule(const char *name)
Return value: Borrowed reference. Part of the Stable ABI.

PyImport_AddModuleObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

PyObject *PyImport_ExecCodeModule(const char *name, PyObject *co)
Return value: New reference. Part of the Stable ABI.

Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module. Return a new reference to the module object, or NULL with an exception set if an error occurred. name is removed from sys.modules in error cases, even if name was already in sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules in sys.modules is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author’s intents) state.

The module’s __spec__ and __loader__ will be set, if not set already, with the appropriate values. The spec’s loader will be set to the module’s __loader__ (if set) and to an instance of SourceFileLoader otherwise.

The module’s __file__ attribute will be set to the code object’s co_filename. If applicable, __cached__ will also be set.

이 함수는 이미 임포트 되었다면 모듈을 다시 로드합니다. 모듈을 다시 로드하는 의도된 방법은 PyImport_ReloadModule()을 참조하십시오.

namepackage.module 형식의 점으로 구분된 이름을 가리키면, 이미 만들어지지 않은 패키지 구조는 여전히 만들어지지 않습니다.

PyImport_ExecCodeModuleEx()PyImport_ExecCodeModuleWithPathnames()도 참조하십시오.

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

PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Return value: New reference. Part of the Stable ABI.

PyImport_ExecCodeModule()과 유사하지만, 모듈 객체의 __file__ 어트리뷰트는 NULL이 아니라면 pathname으로 설정됩니다.

PyImport_ExecCodeModuleWithPathnames()도 참조하십시오.

PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname)
Return value: New reference. Part of the Stable ABI since version 3.7.

PyImport_ExecCodeModuleEx()와 유사하지만, 모듈 객체의 __cached__ 어트리뷰트는 NULL이 아니라면 cpathname으로 설정됩니다. 세 가지 함수 중 이것이 선호되는 것입니다.

버전 3.3에 추가.

버전 3.12에서 변경: Setting __cached__ is deprecated. See ModuleSpec for alternatives.

PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname)
Return value: New reference. Part of the Stable ABI.

PyImport_ExecCodeModuleObject()와 유사하지만, name, pathnamecpathname은 UTF-8로 인코딩된 문자열입니다. pathname의 값이 NULL로 설정된 경우 어떤 값이 cpathname에서 와야하는지 알아내려고 합니다.

버전 3.2에 추가.

버전 3.3에서 변경: Uses imp.source_from_cache() in calculating the source path if only the bytecode path is provided.

버전 3.12에서 변경: No longer uses the removed imp module.

long PyImport_GetMagicNumber()
Part of the Stable ABI.

파이썬 바이트 코드 파일(일명 .pyc 파일)의 매직 번호(magic number)를 반환합니다. 매직 번호는 바이트 코드 파일의 처음 4바이트에 리틀 엔디안 바이트 순서로 존재해야 합니다. 에러 시 -1을 반환합니다.

버전 3.3에서 변경: 실패 시 -1을 반환합니다.

const char *PyImport_GetMagicTag()
Part of the Stable ABI.

PEP 3147 형식 파이썬 바이트 코드 파일 이름의 매직 태그 문자열을 반환합니다. sys.implementation.cache_tag의 값은 신뢰할 수 있고 이 함수 대신 사용해야 함에 유의하십시오.

버전 3.2에 추가.

PyObject *PyImport_GetModuleDict()
Return value: Borrowed reference. Part of the Stable ABI.

모듈 관리에 사용되는 딕셔너리(일명 sys.modules)를 반환합니다. 이것은 인터프리터마다 존재하는 변수임에 유의하십시오.

PyObject *PyImport_GetModule(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.8.

주어진 이름으로 이미 임포트 된 모듈을 반환합니다. 모듈이 아직 임포트 되지 않았다면 NULL을 반환하지만 에러는 설정하지 않습니다. 조회에 실패하면 NULL을 반환하고 에러를 설정합니다.

버전 3.7에 추가.

PyObject *PyImport_GetImporter(PyObject *path)
Return value: New reference. Part of the Stable ABI.

Return a finder object for a sys.path/pkg.__path__ item path, possibly by fetching it from the sys.path_importer_cache dict. If it wasn’t yet cached, traverse sys.path_hooks until a hook is found that can handle the path item. Return None if no hook could; this tells our caller that the path based finder could not find a finder for this path item. Cache the result in sys.path_importer_cache. Return a new reference to the finder object.

int PyImport_ImportFrozenModuleObject(PyObject *name)
Part of the Stable ABI since version 3.7.

name이라는 이름의 프로즌 모듈(frozen module)을 로드합니다. 성공하면 1을, 모듈을 찾지 못하면 0을, 초기화에 실패하면 예외를 설정하고 -1을 반환합니다. 로드가 성공할 때 임포트 된 모듈에 액세스하려면 PyImport_ImportModule()을 사용하십시오. (잘못된 이름에 주의하십시오 — 이 함수는 모듈이 이미 임포트 되었을 때 다시 로드합니다.)

버전 3.3에 추가.

버전 3.4에서 변경: __file__ 어트리뷰트는 더는 모듈에 설정되지 않습니다.

int PyImport_ImportFrozenModule(const char *name)
Part of the Stable ABI.

PyImport_ImportFrozenModuleObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

struct _frozen

이것은 freeze 유틸리티(파이썬 소스 배포의 Tools/freeze/를 참조하십시오)가 생성한 프로즌 모듈 디스크립터를 위한 구조체 형 정의입니다. Include/import.h에 있는 정의는 다음과 같습니다:

struct _frozen {
    const char *name;
    const unsigned char *code;
    int size;
    bool is_package;
};

버전 3.11에서 변경: The new is_package field indicates whether the module is a package or not. This replaces setting the size field to a negative value.

const struct _frozen *PyImport_FrozenModules

This pointer is initialized to point to an array of _frozen records, terminated by one whose members are all NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.

int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Part of the Stable ABI.

기존의 내장 모듈 테이블에 단일 모듈을 추가합니다. 이것은 PyImport_ExtendInittab()을 감싸는 편리한 래퍼인데, 테이블을 확장할 수 없으면 -1을 반환합니다. 새 모듈은 name이라는 이름으로 임포트 될 수 있으며, initfunc 함수를 처음 시도한 임포트에서 호출되는 초기화 함수로 사용합니다. Py_Initialize() 전에 호출해야 합니다.

struct _inittab

Structure describing a single entry in the list of built-in modules. Programs which embed Python may use an array of these structures in conjunction with PyImport_ExtendInittab() to provide additional built-in modules. The structure consists of two members:

const char *name

The module name, as an ASCII encoded string.

PyObject *(*initfunc)(void)

Initialization function for a module built into the interpreter.

int PyImport_ExtendInittab(struct _inittab *newtab)

Add a collection of modules to the table of built-in modules. The newtab array must end with a sentinel entry which contains NULL for the name field; failure to provide the sentinel value can result in a memory fault. Returns 0 on success or -1 if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the internal table. This must be called before Py_Initialize().

If Python is initialized multiple times, PyImport_AppendInittab() or PyImport_ExtendInittab() must be called before each Python initialization.