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

在Python中,有两个相似命名的函数, exit()sys.exit() 。 有什么区别,何时应该使用一个而不是另外一个? html


#1楼

若是我在代码中使用exit()并在shell中运行它,它会显示一条消息,询问我是否要终止该程序。 这真的使人不安。 看这里 python

但在这种状况下, sys.exit()更好。 它会关闭程序而且不会建立任何对话框。 git


#2楼

exit是交互式shell的助手 - sys.exit旨在用于程序。 github

site模块(在启动期间自动导入,除非给出-S命令行选项)将几个常量添加到内置命名空间(例如exit它们对交互式解释器shell颇有用,不该在程序中使用shell


从技术上讲,它们大体相同:提高SystemExitsys.exitsysmodule.c中这样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中定义。 app

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')

请注意,有一个第三个退出选项,即os._exit ,它在不调用清理处理程序,刷新stdio缓冲区等的状况下退出(而且一般只能在fork()以后的子进程中使用)。 ide

相关文章
相关标签/搜索