Python中exit()和sys.exit()之间的区别 [英] Difference between exit() and sys.exit() in Python
问题描述
在Python中,有两个名称相似的函数exit()
和sys.exit()
.有什么区别,什么时候应该在另一个上使用?
In Python, there are two similarly-named functions, exit()
and sys.exit()
. What's the difference and when should I use one over the other?
推荐答案
exit
是交互式外壳程序的帮助程序- sys.exit
是用于程序.
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
site
模块(在启动过程中自动导入,除非提供了-S
命令行选项)内置命名空间(例如exit
). 它们对于交互式解释器外壳很有用,不应在程序中使用.
从技术上讲,它们的作用大致相同:提高 SystemExit
. sys.exit
在 sysmodule.c :
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in 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()
之后的子进程中使用).
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
这篇关于Python中exit()和sys.exit()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!