◐ Shell
clean mode source ↗

bpo-36763: Add _Py_InitializeMain() by vstinner · Pull Request #13362 · python/cpython

@zooba @Yhg1s @ncoghlan: Ok, here you have, a simple change to allow to execute Python code between _Py_InitializeFromConfig() and _Py_InitializeMain(). Using a small change in run_eval_code_obj() (set builtins in globals), it becomes even possible to use import before _Py_InitializeMain() ;-)

See included unit test:

static int test_init_main(void)
{
    _PyCoreConfig config = _PyCoreConfig_INIT;
    configure_init_main(&config);
    config._init_main = 0;

    _PyInitError err = _Py_InitializeFromConfig(&config);
    if (_Py_INIT_FAILED(err)) {
        _Py_ExitInitError(err);
    }

    /* sys.stdout don't exist yet: it is created by _Py_InitializeMain() */
    int res = PyRun_SimpleString(
        "import sys; "
        "print('Run Python code before _Py_InitializeMain', "
               "file=sys.stderr)");
    if (res < 0) {
        exit(1);
    }

    err = _Py_InitializeMain();
    if (_Py_INIT_FAILED(err)) {
        _Py_ExitInitError(err);
    }

    return _Py_RunMain();
}

Maybe _Py_InitializeMain() can be added to PEP 587 as an experimental feature until we decide how to implement PEP 432.