Python解释器在完成代码执行后如何退出?

2024-04-27 08:45:12 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,Python解释器如何退出?在

例如:

print('aaa')

在执行这段代码之后,除了调用注册到atexit的出口处理程序之外,解释器在正常退出(没有引发异常)和不调用os._exit时还做了什么来释放它的资源?在

Python解释器是否在每个出口调用一个主钩子/函数?在

^{pr2}$

Tags: 函数代码处理程序osexit资源解释器钩子
1条回答
网友
1楼 · 发布于 2024-04-27 08:45:12

假设没有调用os._exit(),所有python初始化都以Py_Initialize启动解释器,然后执行给定的python代码,然后将状态代码传递给操作系统。实际上是这样的:

    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也只是引发一个异常,以便解释器干净地退出。在

Is there a main hook/function that the Python interpreter calls on every exit?

试着把你的main()包装起来……最后。在

相关问题 更多 >