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

Viewed 340691

In Python, there are two similarly-named functions, exit() and sys.exit(). What's the difference and when should I use one over the other?

3 Answers

Solution, Origins, Differences & Speed

Why do we need the exit() / sys.exit() commands?

Usually, the code runs through the lines until the end and the program exists automatically. Occasionally, we would like to ask the program to close before the full cycle run. An example case is when you implement authentication and a user fails to authenticate, in some cases you would like to exit the program.

The exit()

Exits Python.

Maybe you didn't know this, but it's a synonym of quit() and was added after quit() to make python more user friendly. Designed to work with interactive shells.

Usage: Use the built-in exit() out of the box, as is, without importing any library. Just type this:

exit()

Execution Time: 0.03s

Pros:

  • Faster to use (built-in)
  • Works both with python 2.x and python 3.x
  • Fast
  • Can be used exactly like sys.exit() (with the exception)

Cons:

  • No exception message

The sys.exit()

Exits Python and raising the SystemExit exception (requires an import). Designed to work inside programs.

Usage:

import sys
sys.exit()

Execution Time (of just the import and sys.exit()): 0.07s

Or you can use a message for the SystemExit exception:

Added finally block to illustrate code cleanup clause. Inspired by @Nairum.

import sys
try:
  sys.exit("This is an exit!")
except SystemExit as error:
  print(error)
finally:
  print("Preforming cleanup in 3, 2, 1..")
  # Do code cleanup on exit

Output:

This is an exit!

Preforming cleanup in 3, 2, 1..

Pros:

  • Triggers SystemExit exception
  • You can use an exception message
  • Closes without a dialog
  • Utilizes finally clause of try
  • Works both with python 2.x and python 3.x

Cons:

  • Needs an import
  • Slower by 57.1% than exit()

Conclusion:

If you don't need an exception with an optional message, then use exit(), this is faster and built-in. If you require more functionality of an exception with an optional message, use sys.exit().

In the code examples I am using Python 3.x

Related