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