Python exit

Complete python exit tutorial with examples in 2023

Python provides many exit functions using which a user can exit the python program. In this blog, we will learn everything about the python exit function. So let’s get started.

Types of python exit function

Python mainly provides four commands using which you can exit from the program and stop the script execution at a certain time. The 4 types of exit commands are:-

  • exit()
  • quit()
  • sys.exit()
  • os._exit()

Python exit() function

The python exit() function is available in the site module. It is used for the exit or termination of a Python script. The exit command should not be used in production and can only be used for interpreters. Below is the sample python code with the exit function.

age = 45
    
if age < 50:  
    # exit the program
    print(exit)
    exit(0) 

This gives the below output:

Python exit() function

You can also use exit() with an argument which is the exit code, for example:

  • exit(0)
  • exit(1)

Python exit(0)

In Python, the exit(0) function is used to exit or terminate a Python script and return an exit code of 0. The exit code 0 is a standard convention to indicate that the program has terminated without errors. Below is the sample python code for exit(0)

age = 45
    
if age < 50:  
    # exit the program
    print(exit)
    exit(0) 

Please note that you can also use exit() with no arguments, which is equivalent to calling sys.exit(0)

Python exit(1)

In Python, the exit(1) function is used to exit or terminate a Python script and return an exit code of 1. Exit code 1 indicates an unsuccessful termination or an error occurred during the execution of the script. Below is the sample python code for exit(1)

age = 45
    
if age &lt; 50:  
    # exit the program
    print(exit)
    exit(1) 

Please note that the exit code of 1 is just a convention and you can use any other integer value to indicate different types of errors.

Python quit() function

In Python, the quit() function is equivalent to the exit() function. However, the quit() function is only available n python2 but not in python 3.Quit() function should only be used in the interpreter. Below is the sample python code which uses the quit() function.

age = 45
    
if age &lt; 50:  
    # quit the program
    print(quit)
    quit()

The above code defines a variable age as 45 and then checks if the value of age is less than 50. If it is, it will print the value of the quit function and then call the quit() function to stop the program from running.

Python quit() function

Python sys.exit() function

In Python, the sys.exit() function is used to exit or terminate a Python script. The sys.exit() function can be used in production because it raises an SystemExit exception that causes the interpreter to exit. You can use the sys.exit() program with or without arguments. With an argument, the program will exit and return a successful exit code on 0, whereas with an argument, which is the exit code like:

  • sys.exit(0) # success
  • sys.exit(1) # failure
import sys
for i in range(1,5):
    print(i)
    if i == 3:
        sys.exit()

The above code will print the numbers from 1 to 3, and then the sys.exit() function will be called when the value of i is 3. This will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination.

Python sys.exit() function

python os._exit() function

In Python, the os._exit() function is used to immediately exit the current process without performing any cleanup or finalization tasks. The os._exit() does not call any cleanup handlers, close open files, or flush stdio buffers. This can make it more efficient for exiting a program, but it also means that any necessary cleanup or finalization tasks will not be executed. It is important to consider the use of os._exit() as it may leave resources open and could cause issues when running in a multi-threaded environment.

Below is the sample python code using the os._exit() function

import os
for i in range(1,5):
    print(i)
    if i == 3:
        os._exit(0)

After the number 3 is printed, the os._exit(0) function will be called, causing the script to immediately terminate and exit the process without printing the remaining numbers (4) in the range.

Python os._exit() function

Python exit vs quit

In Python, the exit() function and quit() function are used to terminate a Python script. Both these functions raise a SystemExit exception, which causes any finally clauses in a try/finally statements to be executed and any unhandled exceptions to be logged.

exit() is a built-in function in both Python2 and Python3, while quit() is a built-in function only in Python2. In Python3 and it is recommended to use exit() or sys.exit() instead.

It’s important to ensure that any resources which the program uses, like file handlers, sockets, or database connections, are closed correctly before exiting the program using exit() or quit() with a non-zero exit code.

Python exit with an error

In Python, you can use the sys.exit() function with a non-zero exit code to exit the program and indicate that an error has occurred. For example:

import sys
for i in range(1,5):
    if i == 3:
        sys.exit("Exiting,as number is equal to 3 ")
    print(i)

In the above code, the script will print the numbers from 1 to 2 and then exit the program when the value of i is 3. The sys.exit() function will be called, which will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination. The message “Exiting, as number is equal to 3” will also be printed before the script exits.

python exit with an error

Python exit from a program gracefully

Exiting a program gracefully refers to allowing the program to perform any necessary cleanup or finalization tasks before terminating. In Python, you can exit a program gracefully by using the sys.exit() function along with finally block to handle any necessary cleanup or finalization tasks.

For example, Below is the sample try-finally block to perform cleanup tasks before exiting the program:

def test():
    try:
        # code to run
    finally:
        # cleanup tasks
        print("Cleanup Done")
        sys.exit(0)

if __name__ == "__main__":
    test()

Conclusion

I hope you have liked this tutorial on the python exit function. Please do let me know if you need further inputs.

More to explore

Python hashmap

Python NULL detailed tutorial

Python ternary

Python lowercase function

Python array length

Python xor function

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top