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


Asked By – Jonathan Livni

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?

Now we will see solution for issue: 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.


  • 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.


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

This question is answered By – Dietrich Epp

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0