Difference between exit() and sys.exit() in Python
在python中,有两个同名的函数:
The
site module (which is imported automatically during startup, except if the-S command-line option is given) adds several constants to the built-in namespace (e.g.exit ). They are useful for the interactive interpreter shell and should not be used in programs.
从技术上讲,他们做的基本相同:提高
1 2 3 4 5 6 7 8 9 10 | 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; } |
而
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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缓冲区等的情况下退出(通常只在
如果我在代码中使用
但在这种情况下,