How does the Python interpreter exit complete the code?

Typically, how does the Python interpreter come out?

For instance:

print('aaa')

After executing this code, in addition to calling output handlers registered with atexit, what else does the interpreter do to free its resources during normal output (without any exceptions) and without calling os._exit?

Is there a main hook / function that the Python interpreter calls on each output?

print('aaa')
_exit()  # called automatically on every exit
+4
source share
1 answer

Assuming it os._exit()doesn't get called, all python initializations start the interpreter with Py_Initialize, then execute the given Python code and then pass the status code to the operating system. This is true:

    n = PyImport_ImportFrozenModule("__main__");
    if (n == 0)
        Py_FatalError("__main__ not frozen");
    if (n < 0) {
        PyErr_Print();
        sts = 1;
    }
    else
        sts = 0;

    if (inspect && isatty((int)fileno(stdin)))
        sts = PyRun_AnyFile(stdin, "<stdin>") != 0;

#ifdef MS_WINDOWS
    PyWinFreeze_ExeTerm();
#endif
    if (Py_FinalizeEx() < 0) {
        sts = 120;
    }

error:
    PyMem_RawFree(argv_copy);
    if (argv_copy2) {
        for (i = 0; i < argc; i++)
            PyMem_RawFree(argv_copy2[i]);
        PyMem_RawFree(argv_copy2);
    }
    PyMem_RawFree(oldloc);
    return sts;

sys.exit , .

/, Python ?

main() try..finally.

+3

Source: https://habr.com/ru/post/1681146/


All Articles