Difference Between Exit() and Sys.Exit() in Python

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

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.


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;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

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')

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 commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported (docs).

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

What is difference between sys.exit(0) and os._exit(0)

According to the documentation:

os._exit():

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().

Difference between exit(0) and exit(1) in Python

0 and 1 are the exit codes.

exit(0) means a clean exit without any errors / problems

exit(1) means there was some issue / error / problem and that is why the program is exiting.

This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was. A zero error code means a successful exit.

This is useful for other programs, shell, caller etc. to know what happened with your program and proceed accordingly.

Difference between calling sys.exit() and throwing exception

sys.exit raises a SystemExit itself so from a purely technical point of view there's no difference between raising that exception yourself or using sys.exit. And yes you can catch SystemExit exceptions like any other exception and ignore it.

So it's just a matter of documenting your intent better.

PS: Note that this also means that sys.exit is actually a pretty bad misnomer - because if you use sys.exit in a thread only the thread is terminated and nothing else. That can be pretty annoying, yes.

Using sys.exit or SystemExit; when to use which?

No practical difference, but there's another difference in your example code - print goes to standard out, but the exception text goes to standard error (which is probably what you want).

What are the reasons to use sys.exit() to wrap a function call?

Read the next part of the documentation that you have linked:

sys.exit([arg])
Raise a SystemExit exception, signaling an intention to exit the interpreter.

The optional argument arg can be an integer giving the exit status.

So the argument is used as an exit code for the current process.

In the cases you mention where we have sys.exit(main()), the main() function itself returns an integer depending on how it ended which is then passed through as an exit code for sys.exit

Python script not stopping on sys.exit()

Sometimes, when writing a multithreadded app, raise SystemExit and sys.exit() both kills only the running thread. On the other hand, os._exit() exits the whole process.

While you should generally prefer sys.exit because it is more "friendly" to other code, all it actually does is raise an exception.

If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit, there is another function - os._exit - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

       #do stuff
if this == that:
quit()

You may try these options!!
Hope it works fine!! If not tell us, we will try more solutions!



Related Topics



Leave a reply



Submit