The Question :
431 people think this question is useful
In Python, there are two similarly-named functions,
sys.exit(). What’s the difference and when should I use one over the other?
The Question Comments :
The Answer 1
490 people think this answer is useful
exit is a helper for the interactive shell –
sys.exit is intended for use in programs.
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.
Technically, they do mostly the same: raising
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))
/* Raise SystemExit so callers may catch it or clean up. */
exit is defined in site.py and _sitebuiltins.py, respectively.
def __init__(self, name):
self.name = name
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.
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
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
The Answer 2
37 people think this answer is useful
If I use
exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It’s really disturbing.
sys.exit() is better in this case. It closes the program and doesn’t create any dialogue box.