在Python中,有两个类似命名的函数,exit()
和sys.exit()
。有什么区别,什么时候应该使用一个而不是另一个?
exit
是交互式shell的助手 - sys.exit
旨在用于程序。
site
模块(在启动期间自动导入,除非给出了-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;
}
而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')
请注意,有第三个退出选项,即os._exit,它退出时不调用清理处理程序,刷新stdio缓冲区等(并且通常只应在fork()
之后的子进程中使用)。
如果我在代码中使用exit()
并在shell中运行它,它会显示一条消息,询问我是否要杀死该程序。这真的令人不安。 See here
但在这种情况下,sys.exit()
更好。它会关闭程序并且不会创建任何对话框。