Python: 5 Ways To Exit & When To Use Which!

In this article, let us see the several options available to us to exit a running Python script and learn when to use which option.

Our aim as developers is to write a script that successfully executes. While most of us seem to focus on that, we must also not forget that knowing how to exit a program is just as crucial.

This ensures that our program can exit gracefully under various scenarios. (For instance, we might need to handle some user errors, log them and terminate our program)

Fortunately, Python provides us with a bunch of options to exit a running code that we can make use of achieve this. This article focuses on answering the following questions

  • What are the available options?
  • How to use each option? and
  • Which one is the best to use in a given scenario?

Excited to learn this concept and level up as a Python programmer? Let’s get started!

Option#1: Using the exit() function

The exit() function is the simplest of all the options we will see today. The syntax for the exit() function is quite straightforward, you can just write ‘exit()’ and it will work:

# 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!")
print("Hi I'm the first print statement!")

You can also pass optional arguments such as a string which would be printed whenever the program exits:

#this line is executed
print("Hi I'm the first print statement!")

exit("Your program is ending now")

#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!
Your program is ending now

However passing an integer altogether has a completely different meaning.

Passing integers to the exit() function (and the other options we will see next) is a way of representing the status of the program exit. By convention, if an integer of 0 is passed, it indicates the successful execution of the program, if a non-zero integer is passed it indicates an error (1 can mean network error, 2 can mean user error,.. etc.)

It must be noted that by default the argument value of the exit() function is 0 if an argument is not provided in our program.

How it works?

It works by simply raising the SystemExit exception whenever you call it.

By the time you reach the end of this article, I suggest you come back and read this summary once more, I assure you it will make much more sense then!

When should you use it?

Short answer: Never!

It is not recommended to use exit() in the production-level code, this is because to use this function, one must import the module named “sitefirst.

You can use it in the interpreter though as the site module is always imported and ready to go in the Python interpreter. This is to make sure that the beginners can use the exit() function to get out of the Python interpreter and get back to the command prompt.

Option#2: Using the quit() function

The quit() function is just an alias for exit() function. These two functions were introduced to make Python user-friendly, because after all one of the first things something new to Python programming will try to do to exit or quit the interpreter is to write ‘quit’. The syntax to use quit() is the same as for exit().

Again, the quit() function is also not recommended to be used in the production-level code as this too relies on the site module. 

Option#3: Using sys.exit()

sys.exit() is another exit command that is from the sys module. When called, this function terminates the program by raising the SystemExit exception just like the exit() and quit() functions.

However, unlike those two, the sys.exit() is recommended to be used in production code. That is because the sys module will always be installed(whereas site might not be available). Hence, using this method is considered the standard way of exiting the program!

Let’s see this in action:

Just like the last two functions, the sys.exit() function also takes in optional arguments which can be a string, integer, or any other object.

Let’s see how that works with an example

import sys

user_input = input("Please enter the word 'yes': ")

if user_input != 'yes':
    print("You did not enter 'yes'. Exiting the program...")
    sys.exit()
    # the following statement can also do the same:
    # sys.exit("You did not enter 'yes'. Exiting the program...")
    
else:
    print("You entered the word 'yes'. Continuing the program...")
Please enter the word 'yes': no
You did not enter 'yes'. Exiting the program...
Please enter the word 'yes': yes
You entered the word 'yes'. Continuing the program...

In the above example, if the user inputs as instructed, the program is designed to move on further to the next set of statements, otherwise if they do not enter the required input we exit the program.

We can also terminate it with an exit status of ‘1’ to indicate something went wrong.

It must be noted that the sys.exit() function exits the program by raising the SystemExit exception when called. So if you plan to perform clean-up activities it can be done by using the try-except blocks!  

Note: It is always recommended that you include a cleanup code if your program uses resources that need to be dealt with (you might want to close or release them). This ensures that the resources are handled gracefully even if the program exits abruptly.

When to use sys.exit()?

As mentioned earlier, the sys.exit() is more elegant and is the standard way of exiting in Python as compared to exit() and quit() functions.

Another advantage the sys.exit() has over the exit() function is that the sys.exit() function can be rewritten and customized to suit your needs. We have an entire article dedicated to customizing exceptions, you can find that in the link below.

Custom Exceptions in Python: Everything You Need to Know!

Using sys.exit() in multi-threaded programs

If your code has threads, care must be taken to ensure that the other threads are not affected if one thread exits. I leave it to you to figure this one out as it depends so much on the nature of your code.

Option#4: Using raise SytemExit

In this method of quitting the program, we are manually raising the SystemExit exception which then leads to the program termination

Raising SytemExit is pretty much what the exit(), quit(), and sys.exit() does in the background. This is just a straightforward way of writing the same code! 

When to use? (Raising SystemExit)

Whilst they do the same thing at the end of the day, it must be noted that the more elegant and standard way is to use the sys.exit() wrapper.

Another advantage of using sys.exit() over manually raising the SystemExit exception is that the sys.exit() can be overwritten and customized as per our needs.

Option#5: Using os._exit()

The os module’s exit() function, a.k.a os._exit() exits your program in a different way. When you call it, it immediately exits the function by calling the underlying os function directly.

This is different from the other methods as the os._exit() does not allow Python to run its normal exit process. It exits without giving us a chance to perform any cleanup activities like closing files, databases, network connections, etc.

This is the reason the os._exit() function is not considered the standard way of exiting the program. It is recommended to generally avoid it unless in specific scenarios such as when SystemExit does not work!

Also, the os._exit() requires an integer argument that represents the status of the execution of the program. We cannot leave it empty or pass arguments of other types as we did for the other exit commands, which leads to a TypeError.

Here’s an example:

import os

print("Hello world!")

os._exit(1)

print("Goodbye world!")
Hello world!

Remember, since os._exit() function brutally kills the program, it is generally not suggested to use it in day-to-day programs!

In other words, only use it if you are an experienced developer and you know what you’re doing!

When to use? (the abrupt way of exiting)

Whilst generally it is not recommended to use this method, there may be special circumstances demanding os.exit(). 

The os.exit() method is useful in scenarios where an error occurs and you need to shut the program down as quickly as possible to stop any further damages.

Conclusion

When to use which one?

Whilst each method seems to do the same thing in different ways, the best way has to be the sys.exit() method.

The keyboard interruption method is quick but it raises the KeyboardInterrupt exception.

On the other hand, exit() and quit() are not recommended to be used in production-level code. And let’s not even talk about os._exit() which is an overkill.

The sys.exit() is a convenient option that can be used anywhere at any time with the only disadvantage being that you need to import the sys module before its usage.

In other words,

  • feel free to use the exit(), and quit() options when you’re using the interactive console.
  • If the SystemExit is not quick enough and you wish to stop further damages, you can use the os._exit() function.
  • Otherwise, the sys.exit() method gets the thumbs up for everyday programming challenges!

Now that we have learnt how to exit programs, next I invite you to learn how to debug exceptions like a pro!

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!

Related Articles

Python: How to Create a Custom Exception

Python: “try-except-else-finally” Usage Explained!

“Exception” Class in Python: A Walk-through!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn