python

Python exit commands - why so many and when should each be used?


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?


Solution

  • 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

    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.