exit是交互式shell的帮助程序 - sys.exit旨在用于程序 .
站点模块(在启动期间自动导入,除非给出了-S命令行选项)向内置命名空间添加了几个常量(例如exit) . 它们对交互式解释器shell很有用,不应在程序中使用 .
从技术上讲,他们大致相同:提高SystemExit . sys.exit 在sysmodule.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;
}
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() 之后的子进程中使用) .