657

It seems that python supports many different commands to stop script execution.
The choices I've found are: quit(), exit(), sys.exit(), os._exit()

Have I missed any? What's the difference between them? When would you use each?

Jackie
  • 21,969
  • 32
  • 147
  • 289
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

4 Answers4

961

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

    Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>
    

    This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

    Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  2. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

    Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>
    

    However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  3. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

    Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  4. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

    Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

mhsmith
  • 6,675
  • 3
  • 41
  • 58
  • 3
    But in ipython shell, `quit` and `exit` quit the shell while `sys.exit` doesn't. – wsdzbm May 25 '16 at 17:41
  • 22
    `sys.exit()` is not a reliable way to close down. If it is called inside a thread, it will terminate only that thread unless it is in the main thread. This can lead to a lot of cases where the program continues because the call was not in the main thread, especially as some interpreters will invisibly thread calls. – Elliot Mar 16 '18 at 16:47
  • 3
    I vote for adding an `end` command which would `raise SystemExit`. Don't see why there can't be something simple like that, as in BASIC. – Brian Burns Oct 09 '18 at 10:21
  • 13
    @BrianBurns: It's not worth adding dedicated syntax and reserving another keyword. This is similar to why `print` was changed from a statement to a function. It's easy to add syntax, but there's a complexity cost in doing so. – user2357112 Dec 07 '18 at 19:58
  • 7
    `raise SystemExit` is fantastic even if the sys library is not available in some restricted python environment – radke Mar 13 '19 at 18:48
  • @iCodez - I've had a script running and it opens a pool to do some requests - and I have an `exit(0)` at the end (the built in) and also tried `sys.exit()` - although I noticed the processes remain open in `ps -x` - without any `exit()` the processes die off. – Julian Camilleri Jun 05 '19 at 11:16
  • 1
    Is is just me, or would it be possible and even likely for some code to except all Exceptions and still run after SystemExit was raised? Even intermediate tutorials use this approache occasionally. Call an API, except and handle any Exception you can anticipate, except all Exceptions, log and do a default handling. (I checked the doc, so I know it's true). Is that generally bad practice or is it intended to overrule an exit filed by 3rd party code? – hajef Jun 27 '19 at 09:09
  • Do these exit all running python scripts or just the script one is in? Also, if these commands are inside a method that is inside a module that is imported by my python script and called by that python script, will everything close? – rfii Aug 15 '20 at 19:27
  • 1
    @hajef Catching a SystemExit() is possible and intended. This is done by debuggers and some IDEs to allow the Python interpreter to not exit. I would recommend catching the most specific exceptions possible for the general case. I would assume a tutorial recommending catching all exceptions is likely assuming a SystemExit() won't occur. – The Matt Dec 24 '20 at 02:02
  • **Exit(result)** makes better sense. It's unclear what code **raise SystemExit** returns. This can be very important if other scripts need to know if your program was successfully executed. – ATL_DEV Sep 01 '22 at 20:50
  • @hajef While it is possible (and intended) to catch a `SystemExit`, just saying `except Exception` won't do it, as `SystemExit` inherits from `BaseException` directly exactly for that purpose. – schtandard Jun 12 '23 at 08:45
139

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.

djvg
  • 11,722
  • 5
  • 72
  • 103
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
66

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

Mike Williamson
  • 4,915
  • 14
  • 67
  • 104
  • 9
    "_Otherwise mainly use exit() or quit()._" Even though the [documentation](https://docs.python.org/3/library/constants.html#constants-added-by-the-site-module) states "They are useful for the interactive interpreter shell and **should not be used in programs**."? – wovano Aug 12 '20 at 11:35
  • 4
    There is also `exit("Here is why the program failed")`, which prints the error message and exits with return status `1`. – Jasha Jun 10 '21 at 21:48
  • 1
    “`quit()`: Closes the python file.” ??? – Alex Peters Apr 17 '22 at 07:55
46

sys.exit is the canonical way to exit.

Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

os.exit is a low-level system call that exits directly without calling any cleanup handlers.

quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$

This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
oefe
  • 19,298
  • 7
  • 47
  • 66