解释器初始化和最终化¶
请参阅 Python 初始化配置 了解如何在初始化之前配置解释器的详情。
Before Python initialization¶
In an application embedding Python, the Py_Initialize() function must
be called before using any other Python/C API functions; with the exception of
a few functions.
在初始化 Python 之前,可以安全地调用以下函数:
初始化解释器的函数:
配置函数:
PyInitFrozenExtensions()配置相关函数在 Python 初始化配置 中介绍
信息函数:
工具:
状态报告和工具相关函数在 Python 初始化配置 中介绍
内存分配器:
同步:
备注
Despite their apparent similarity to some of the functions listed above,
the following functions should not be called before the interpreter has
been initialized: Py_EncodeLocale(), and Py_RunMain().
初始化和最终化解释器¶
-
void Py_Initialize()¶
- 属于 稳定 ABI.
Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; see Before Python Initialization for the few exceptions.
这将初始化已加载的模块表 (
sys.modules),并创建基础模块builtins,__main__和sys。它还会初始化模块搜索路径 (sys.path)。它不会设置sys.argv;对于此设置请使用 Python 初始化配置 API。当第二次被调用时(在未先调用Py_FinalizeEx()的情况下)将不会执行任何操作。它没有返回值;如果初始化失败则会发生致命错误。使用
Py_InitializeFromConfig()来自定义 Python 初始化配置。备注
在 Windows 上,将控制台模式从
O_TEXT改为O_BINARY,这还将影响使用 C 运行时的非 Python 的控制台使用。
-
void Py_InitializeEx(int initsigs)¶
- 属于 稳定 ABI.
如果 initsigs 为
1则此函数的工作方式与Py_Initialize()类似。如果 initsigs 为0,它将跳过信号处理器的初始化注册,这在将 CPython 作为更大应用程序的一部分嵌入时会很有用处。使用
Py_InitializeFromConfig()来自定义 Python 初始化配置。
-
PyStatus Py_InitializeFromConfig(const PyConfig *config)¶
根据 config 配置来初始化 Python,如 使用 PyConfig 初始化 中所描述的。
请参阅 Python 初始化配置 一节了解有关预初始化解释器,填充运行时配置结构体,以及查询所返回的状态结构体的详情。
在 3.16.0a0 (unreleased) 版本发生变更: The function no longer returns an exit code if a command line option wants to exit Python. Instead, the option is processed in
Py_RunMain().
-
int Py_IsInitialized()¶
- 属于 稳定 ABI.
如果 Python 解释器已初始化,则返回真值(非零);否则返回假值(零)。在调用
Py_FinalizeEx()之后,此函数将返回假值直到Py_Initialize()再次被调用。在 3.15 版本发生变更: This function no longer returns true until initialization has fully completed, including import of the
sitemodule. Previously it could return true whilePy_Initialize()was still running.
-
int Py_IsFinalizing()¶
- 属于 稳定 ABI 自 3.13 版起.
如果主 Python 解释器 正在关闭 则返回真(非零)值。在其他情况下返回假(零)值。
Added in version 3.13.
-
int Py_FinalizeEx()¶
- 属于 稳定 ABI 自 3.6 版起.
撤销由
Py_Initialize()所执行的所有初始化操作及后续对 Python/C API 函数的使用,并销毁自上次调用Py_Initialize()以来创建但尚未销毁的所有子解释器(参见下面Py_NewInterpreter()一节)。 当第二次调用(事先没有再次对Py_Initialize()进行调用)时将无任何操作。由于这是
Py_Initialize()的逆向操作,因而它应当在激活同一解释器的同一线程中被调用。这意味着主线程和主解释器。当Py_RunMain()仍然运行时则绝不应调用此函数。通常返回值为
0。如果在最终化(刷新缓冲的数据)期间发生错误,则返回-1。请注意 Python 会尽最大努力释放 Python 解释器所分配的所有内存。 因此,任何 C 扩展都应当确保在对
Py_Initialize()的后续调用中使用此前分配的所有 PyObjects 之前正确地清理它们。 否则可能导致安全漏洞和不正确的行为。提供此函数的原因有很多。嵌入应用程序可能希望重新启动 Python,而不必重新启动应用程序本身。从动态可加载库(或 DLL)加载 Python 解释器的应用程序可能希望在卸载 DLL 之前释放 Python 分配的所有内存。在搜索应用程序内存泄漏的过程中,开发人员可能希望在退出应用程序之前释放 Python 分配的所有内存。
已知问题与注意事项: 模块及模块内对象的销毁顺序是随机的,这可能导致析构器 (
__del__()方法) 在依赖其他对象(甚至函数)或模块时执行失败; 由 Python 动态加载的扩展模块不会被卸载; Python 解释器分配的少量内存可能无法释放(如发现内存泄漏请提交报告); 对象间循环引用占用的内存不会被释放; 无论引用计数如何,所有驻留字符串(interned strings)都将被释放; 扩展模块分配的部分内存可能无法释放; 某些扩展在初始化例程被多次调用时可能出现异常行为(当应用程序多次调用Py_Initialize()和Py_FinalizeEx()时会发生这种情况);Py_FinalizeEx()不可被自身递归调用,因此任何可能作为解释器关闭流程一部分的代码(如atexit处理器、对象终结器、或在刷新 stdout/stderr 文件时运行的代码)都不得调用该函数。引发一个不带参数的 审计事件
cpython._PySys_ClearAuditHooks。Added in version 3.6.
-
void Py_Finalize()¶
- 属于 稳定 ABI.
这是一个不考虑返回值的
Py_FinalizeEx()的向下兼容版本。
-
int Py_BytesMain(int argc, char **argv)¶
- 属于 稳定 ABI 自 3.8 版起.
类似于
Py_Main()但 argv 是一个字节串数组,允许调用方应用程序将文本解码步骤委托给 CPython 运行时。Added in version 3.8.
-
int Py_Main(int argc, wchar_t **argv)¶
- 属于 稳定 ABI.
标准解释器的主程序,封装了完整的初始化/最终化循环,以及一些附加行为以实现从环境和命令行读取配置设置,然后按照 命令行 的规则执行
__main__。这适用于希望支持完整 CPython 命令行界面的程序,而不仅是在更大应用程序中嵌入 Python 运行时。
argc 和 argv 形参与传给 C 程序的
main()函数的形参类似,不同之处在于 argv 的条目会先使用Py_DecodeLocale()转换为wchar_t。 还有一个重要的注意事项是参数列表条目可能会被修改为指向并非被传入的字符串(不过,参数列表所指向的字符串内容不会被修改)。如果参数列表不是表示一个有效的 Python 命令行则返回值为
2,否则将与Py_RunMain()相同。在记录于 运行时配置 一节的 CPython 运行时配置 API 文档中(不考虑错误处理),
Py_Main大致相当于:PyConfig config; PyConfig_InitPythonConfig(&config); PyConfig_SetArgv(&config, argc, argv); Py_InitializeFromConfig(&config); PyConfig_Clear(&config); Py_RunMain();
在正常使用中,嵌入式应用程序将调用此函数 而不是 直接调用
Py_Initialize(),Py_InitializeEx()或Py_InitializeFromConfig(),并且所有设置都将如本文档的其他部分所描述的那样被应用。 如果此函数改在某个先前的运行时初始化 API 调用 之后 被调用,那么到底那个环境和命令行配置会被更新将取决于具体的版本(因为它要依赖当运行时被初始化时究竟有哪些设置在它们已被设置一次之后是正确地支持被修改的)。
-
int Py_RunMain(void)¶
在完整配置的 CPython 运行时中执行主模块。
执行在命令行或配置中指定的命令 (
PyConfig.run_command)、脚本 (PyConfig.run_filename) 或模块 (PyConfig.run_module)。 如果这些值均未设置,则使用__main__模块的全局命名空间来运行交互式 Python 提示符 (REPL)。如果
PyConfig.inspect未设置(默认),则当解释器正常退出(也就是说未引发异常)时返回值将为0,未处理的SystemExit的退出状态,或者对于任何其他未处理异常则为1。如果
PyConfig.inspect已设置(例如当使用了-i选项时),则当解释器退出时执行将不会返回,而是会使用__main__模块的全局命名空间在交互式 Python 提示符 (REPL) 中恢复。 如果解释器附带异常退出,该异常将在 REPL 会话中被立即引发。随后函数的返回值将由 REPL 会话 的终结方式来决定:0,1或者SystemExit的状态,如上文所指明的。此函数总是会在它返回之前最终化 Python 解释器。
请参阅 Python 配置 查看一个使用
Py_RunMain()在隔离模式下始终运行定制的 Python 的示例。
-
int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void*), void *data)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
为目标解释器 interp 注册一个
atexit回调。这与Py_AtExit()类似,但它接受一个显式的解释器和用于回调的数据指针。必须有一个对应 interp 的 attached thread state。
Added in version 3.13.
Cautions regarding interpreter finalization¶
In the late stage of interpreter shutdown, after attempting to wait for
non-daemon threads to exit (though this can be interrupted by
KeyboardInterrupt) and running the atexit functions, the runtime
is marked as finalizing, meaning that Py_IsFinalizing() and
sys.is_finalizing() return true. At this point, only the finalization
thread (the thread that initiated finalization; this is typically the main thread)
is allowed to attach a thread state.
Other threads that attempt to attach during finalization, either explicitly
(such as via PyThreadState_Ensure() or Py_END_ALLOW_THREADS)
or implicitly (such as in-between bytecode instructions), will enter a
permanently blocked state. Generally, this is harmless, but this can
result in deadlocks. For example, a thread may be permanently blocked while
holding a lock, meaning that the finalization thread can never acquire that
lock.
Prior to CPython 3.13, the thread would exit instead of hanging,
which led to other issues (see the warning note at
PyThread_exit_thread()).
Gross? Yes. Starting in Python 3.15, there are a number of C APIs that make it possible to avoid these issues by temporarily preventing finalization:
参见
PEP 788 explains the design, motivation and rationale for these APIs.
-
type PyInterpreterGuard¶
- 属于 稳定 ABI (作为不透明的结构体) 自 3.15 版起.
An opaque interpreter guard structure.
By holding an interpreter guard, the caller can ensure that the interpreter will not finalize until the guard is closed (through
PyInterpreterGuard_Close()).When a guard is held, a thread attempting to finalize the interpreter will block until the guard is closed before starting finalization. After finalization has started, threads are forever unable to acquire guards for that interpreter. This means that if you forget to close an interpreter guard, the process will permanently hang during finalization!
Holding a guard for an interpreter is similar to holding a strong reference to a Python object, except finalization does not happen automatically after all guards are released: it requires an explicit
Py_EndInterpreter()call.Added in version 3.15.
-
PyInterpreterGuard *PyInterpreterGuard_FromCurrent(void)¶
- 属于 稳定 ABI 自 3.15 版起.
Create a finalization guard for the current interpreter. This will prevent finalization until the guard is closed.
例如:
// Temporarily prevent finalization. PyInterpreterGuard *guard = PyInterpreterGuard_FromCurrent(); if (guard == NULL) { // Finalization has already started or we're out of memory. return NULL; } Py_BEGIN_ALLOW_THREADS; // Do some critical processing here. For example, we can safely acquire // locks that might be acquired by the finalization thread. Py_END_ALLOW_THREADS; // Now that we're done with our critical processing, the interpreter is // allowed to finalize again. PyInterpreterGuard_Close(guard);
On success, this function returns a guard for the current interpreter; on failure, it returns
NULLwith an exception set.This function will fail only if the current interpreter has already started finalizing, or if the process is out of memory.
The guard pointer returned by this function must be eventually closed with
PyInterpreterGuard_Close(); failing to do so will result in the Python process infinitely hanging.调用方必须持有一个 attached thread state。
Added in version 3.15.
-
PyInterpreterGuard *PyInterpreterGuard_FromView(PyInterpreterView *view)¶
- 属于 稳定 ABI 自 3.15 版起.
Create a finalization guard for an interpreter through a view.
On success, this function returns a guard to the interpreter represented by view. The view is still valid after calling this function. The guard must eventually be closed with
PyInterpreterGuard_Close().If the interpreter no longer exists, is already finalizing, or out of memory, then this function returns
NULLwithout setting an exception.调用方不需要持有 attached thread state。
Added in version 3.15.
-
void PyInterpreterGuard_Close(PyInterpreterGuard *guard)¶
- 属于 稳定 ABI 自 3.15 版起.
Close an interpreter guard, allowing the interpreter to start finalization if no other guards remain. If an interpreter guard is never closed, the interpreter will infinitely wait when trying to enter finalization!
After an interpreter guard is closed, it may not be used in
PyThreadState_Ensure(). Doing so will result in undefined behavior.This function cannot fail, and the caller doesn't need to hold an attached thread state.
Added in version 3.15.
Interpreter views¶
In some cases, it may be necessary to access an interpreter that may have been deleted. This can be done using interpreter views.
-
type PyInterpreterView¶
- 属于 稳定 ABI (作为不透明的结构体) 自 3.15 版起.
An opaque view of an interpreter.
This is a thread-safe way to access an interpreter that may have be finalizing or already destroyed.
Added in version 3.15.
-
PyInterpreterView *PyInterpreterView_FromCurrent(void)¶
- 属于 稳定 ABI 自 3.15 版起.
Create a view to the current interpreter.
This function is generally meant to be used alongside
PyInterpreterGuard_FromView()orPyThreadState_EnsureFromView().On success, this function returns a view to the current interpreter; on failure, it returns
NULLwith an exception set.调用方必须持有一个 attached thread state。
Added in version 3.15.
-
void PyInterpreterView_Close(PyInterpreterView *view)¶
- 属于 稳定 ABI 自 3.15 版起.
Close an interpreter view.
If an interpreter view is never closed, the view's memory will never be freed, but there are no other consequences. (In contrast, forgetting to close a guard will infinitely hang the main thread during finalization.)
This function cannot fail, and the caller doesn't need to hold an attached thread state.
Added in version 3.15.
-
PyInterpreterView *PyInterpreterView_FromMain(void)¶
- 属于 稳定 ABI 自 3.15 版起.
Create a view for the main interpreter (the first and default interpreter in a Python process; see
PyInterpreterState_Main()).On success, this function returns a view to the main interpreter; on failure, it returns
NULLwithout an exception set. Failure indicates that the process is out of memory.Use this function when an interpreter pointer or view cannot be supplied by the caller, such as when a native threading library does not provide a
void *argparameter that could carry aPyInterpreterGuardorPyInterpreterView. In code that supports subinterpreters, preferPyInterpreterView_FromCurrent()so the guard tracks the calling interpreter rather than the main one.调用方不需要持有 attached thread state。
Added in version 3.15.
进程级参数¶
-
const char *Py_GetVersion()¶
- 属于 稳定 ABI.
返回 Python 解释器的版本。这将为如下形式的字符串
"3.15.0rc2 (3.15.0~rc2-1.fc44.x86_64, Sep 3 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]"第一个单词(到第一个空格符为止)是当前的 Python 版本;前面的字符是以点号分隔的主要和次要版本号。 返回的字符串将指向静态存储;调用方不应修改其值。该值将以
sys.version的名称供 Python 代码使用。另请参阅
Py_Version常量。
-
const char *Py_GetPlatform()¶
- 属于 稳定 ABI.
返回当前平台的平台标识符。在 Unix 上,这将以操作系统的“官方”名称为基础,转换为小写形式,再加上主版本号;例如,对于 Solaris 2.x,或称 SunOS 5.x,该值将为
'sunos5'。在 macOS 上,它将为'darwin'。在 Windows 上它将为'win'。返回的字符串指向静态存储;调用方不应修改其值。Python 代码可通过sys.platform获取该值。
-
const char *Py_GetCopyright()¶
- 属于 稳定 ABI.
返回当前 Python 版本的官方版权字符串,例如
'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'返回的字符串指向静态存储;调用者不应修改其值。Python 代码可通过
sys.copyright获取该值。