Python中exit()和sys.exit()的区别

2024-03-29 10:19:10 发布

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

在Python中,有两个名称类似的函数,exit()sys.exit()。有什么区别?我应该什么时候用一个?


Tags: 函数名称sysexit区别
2条回答

如果我在代码中使用exit()并在shell中运行它,它将显示一条消息,询问是否要终止程序。真令人不安。 See here

但在这种情况下sys.exit()更好。它关闭程序,不创建任何对话框。

^{}是交互式shell的助手-^{}用于程序中。

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


从技术上讲,它们基本上是一样的:提高^{}sys.exitsysmodule.c中这样做:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

exit分别在site.py_sitebuiltins.py中定义。

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

注意,还有第三个exit选项,即os._exit,它在不调用清理处理程序、刷新stdio缓冲区等的情况下退出(通常只应在fork()之后的子进程中使用)。

相关问题 更多 >