In this article, we will take a look at the exit() function and learn how to use it the right way! (Yes there is more than one wrong way of using it!)
In particular, we will be answering the following questions
- What is the exit() function?
- What arguments does it accept and what are their meanings?
- How to clean up the resources during exit? and
- When NOT to use exit() and what to use instead in those situations?
Let us start with a quick refresher on the exit() function.
What is the exit() function?
The exit() function can be used to exit at any given point in your Python script. When called, it stops the execution of your program by raising the SystemExit exception. When this exception is raised and left unhandled, the Python interpreter exits!
The exit() function in action
Here is a simple and short example of showing how the exit() function works in Python
#this line is executed print("Hi I'm the first print statement!") exit() #the program has ended and this line will not be executed print("Hi I'm the second print statement!")
Hi I'm the first print statement!
As you can see, the script successfully stopped executing after the exit() function was called as the 2nd print statement wasn’t executed.
From that example, you may think that the syntax is simply just calling it exit(). But wait, there’s more! You can actually add optional arguments, let’s have a look at them!
Passing arguments to exit()
Python allows us to add optional arguments to our function. They can be either strings or integers.
If you pass in a string as your argument to the exit() function, it will print the string and exit the script:
exit("The program is ending, bye!") print("The program has ended so this won't be printed!")
The program is ending, bye!
On the other hand, passing integers to the exit() is a way of showing the program’s exit status.
If you pass 0 as your exit status, it indicates successful execution of the program:
On the other hand, any non-zero termination of the program shows an abnormal termination of your program, for example:
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. (Source)
This way of giving out an integer is a convention used with all programming languages not just Python. A non-zero exit code is treated as an abnormal exit, and at times. A zero error code means a successful exit.
The non-zero number (error code) is usually mapped to a particular error by the programmer. This value can then be used by other programs such as shell, caller, etc. to know what happened with your program and proceed accordingly.
How to clean up on the call to exit( )
It is always recommended to use clean-up code when exiting your program so that resources are not left hanging and we don’t end up with corrupted files or databases, which is never good!
For example, we can close any open files while exiting as shown in the example below.
def process_file(file_path): try: file = open(file_path, 'r') for line in file: print(line) except: print("Oops, error!") exit(0) finally: try: file.close() #This is to handle the case where an exception has occurred before the file was opened except: print("The file wasn't opened due to an error. Hence there is no file to be closed.") file_path = "example.txt" process_file(file_path) print("This won't be printed!")
It is recommended to keep the cleanup code in the finally block
If you are not familiar with the usage of finally, I suggest setting aside 10 mins and reading the following article.
Python: “try-except-else-finally” Usage Explained!
- We keep the code that is susceptible to raising an error in the try block. We try to open a file and print its contents in this case.
- We catch any triggered exceptions in the except block. In this case, it might be a FileNotFoundError, PermissionError, etc.
- If the program has faced a problem, we exit it using the exit() method placed in the except block. It must be noted that the exit() method allows the finally block to be executed before it terminates the program.
- The finally block contains the cleanup code like closing the file handler to save memory and the program is terminated
- Since the program is terminated, notice how the last print statement is not executed
When should you use exit()
Always keep in mind that it is not recommended to use exit() in the production-level code. That’s because you’ll have to install the site module first to use it and this module may not be available every time in the production environment.
Alternatively, you can use sys.exit() in the production code. To learn more about it, I invite you to read our other article dedicated to it in the link below.
The exit() function works best when you are coding in REPL a.k.a the Python interpreter console.
And with that, I will end this article.
Congratulations on making it to the end of the article, not many have the perseverance to do so!
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Thanks to Namazi Jamal for his contributions in writing this article!