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?
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?
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.
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:
sys.exit() (with the exception)Cons:
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:
finally clause of tryCons:
exit()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