<p><a href="http://docs.python.org/library/constants.html#exit" rel="noreferrer">^{<cd1>}</a>是交互式shell的助手-<a href="http://docs.python.org/library/sys.html#sys.exit" rel="noreferrer">^{<cd2>}</a>用于程序中。</p>
<blockquote>
<p>The <a href="https://docs.python.org/library/site.html#module-site" rel="noreferrer"><code>site</code></a> module (which is imported automatically during startup, except if the <a href="https://docs.python.org/using/cmdline.html#id3" rel="noreferrer"><code>-S</code></a> command-line option is given) adds several constants to the built-in namespace <em>(e.g. <code>exit</code>)</em>. <strong>They are useful for the interactive interpreter shell and should not be used in programs</strong>.</p>
</blockquote>
<hr/>
<p>从技术上讲,它们基本上是一样的:提高<a href="https://docs.python.org/library/exceptions.html#SystemExit" rel="noreferrer">^{<cd3>}</a>。<code>sys.exit</code>在<a href="https://github.com/python/cpython/blob/06fe77a84bd29d51506ab2ff703ae585a6121af2/Python/sysmodule.c#L337-L346" rel="noreferrer"><em>sysmodule.c</em></a>中这样做:</p>
<pre class="lang-c prettyprint-override"><code>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;
}
</code></pre>
<p>而<code>exit</code>分别在<a href="https://github.com/python/cpython/blob/06fe77a84bd29d51506ab2ff703ae585a6121af2/Lib/site.py#L365-L366" rel="noreferrer">site.py</a>和<a href="https://github.com/python/cpython/blob/06fe77a84bd29d51506ab2ff703ae585a6121af2/Lib/_sitebuiltins.py#L13-L26" rel="noreferrer">_sitebuiltins.py</a>中定义。</p>
<pre><code>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')
</code></pre>
<hr/>
<p>注意,还有第三个exit选项,即<a href="http://docs.python.org/library/os.html#os._exit" rel="noreferrer">os._exit</a>,它在不调用清理处理程序、刷新stdio缓冲区等的情况下退出(通常只应在<code>fork()</code>之后的子进程中使用)。</p>