Python 初始化設定¶
PyInitConfig C API¶
在 3.14 版被加入.
Python 可以使用 Py_InitializeFromInitConfig() 來初始化。
The Py_RunMain() function can be used to write a customized Python
program.
See also Initialization, Finalization, and Threads.
也參考
PEP 741 "Python Configuration C API".
範例¶
Example of customized Python always running with the Python Development
Mode enabled; return -1 on error:
int init_python(void)
{
PyInitConfig *config = PyInitConfig_Create();
if (config == NULL) {
printf("PYTHON INIT ERROR: memory allocation failed\n");
return -1;
}
// Enable the Python Development Mode
if (PyInitConfig_SetInt(config, "dev_mode", 1) < 0) {
goto error;
}
// Initialize Python with the configuration
if (Py_InitializeFromInitConfig(config) < 0) {
goto error;
}
PyInitConfig_Free(config);
return 0;
error:
{
// Display the error message.
//
// This uncommon braces style is used, because you cannot make
// goto targets point to variable declarations.
const char *err_msg;
(void)PyInitConfig_GetError(config, &err_msg);
printf("PYTHON INIT ERROR: %s\n", err_msg);
PyInitConfig_Free(config);
return -1;
}
}
建立設定¶
-
struct PyInitConfig¶
Opaque structure to configure the Python initialization.
-
PyInitConfig *PyInitConfig_Create(void)¶
Create a new initialization configuration using Isolated Configuration default values.
必須由
PyInitConfig_Free()來釋放。在記憶體配置失敗時回傳
NULL。
-
void PyInitConfig_Free(PyInitConfig *config)¶
釋放初始化配置 config 的記憶體。
如果 config 是
NULL,則不執行任何操作。
錯誤處理¶
-
int PyInitConfig_GetError(PyInitConfig *config, const char **err_msg)¶
取得 config 錯誤訊息。
如果設定了錯誤,則設置 *err_msg 並回傳
1。如果沒有設定錯誤,則設定 *err_msg 為
NULL並回傳0。
錯誤訊息是 UTF-8 編碼的字串。
If config has an exit code, format the exit code as an error message.
The error message remains valid until another
PyInitConfigfunction is called with config. The caller doesn't have to free the error message.
-
int PyInitConfig_GetExitCode(PyInitConfig *config, int *exitcode)¶
Get the config exit code.
Set *exitcode and return
1if config has an exit code set.Return
0if config has no exit code set.
Only the
Py_InitializeFromInitConfig()function can set an exit code if theparse_argvoption is non-zero.An exit code can be set when parsing the command line failed (exit code
2) or when a command line option asks to display the command line help (exit code0).
Get Options¶
The configuration option name parameter must be a non-NULL null-terminated UTF-8 encoded string. See Configuration Options.
-
int PyInitConfig_HasOption(PyInitConfig *config, const char *name)¶
測試配置是否有名為