Why is Python sys.exit better than other exit functions?

There are many times when we want to exit from the programs after a particular code gets executed, without even reaching the end of the program. There are many ways in python to exit from the program, which, if you want to know, you can click on this link. Despite having so many ways, python programmers/ developers generally prefer using sys.exit in the real world. 

When sys.exit is called, it raises a SystemExit Exception. In this article, we will learn how to use sys.exit, what arguments we can pass, when it should be used, and many more important things. 

Syntax of sys.exit()

Whenever we want to exit from the interpreter explicitly, it means whenever we want to exit from the program before the interpreter reaches the end of the program, we can use sys.exit.  

Before using sys.exit, we first need to import the ‘sys’ module into our systems. To import use – ‘import sys.’ 

sys.exit([status]) 

Parameter of sys.exit in python

sys.exit accepts only one argument – status, and that too is optional. If we want to print something while exiting like why we want to exit or something, we can pass that in the argument. It can be either an integer, float, boolean, or string. 

Return Type

sys.exit returns SystemExit Exception along with the passed argument. 

Note If we are passing integer 0 as the argument, it means the termination is successful, and if we pass any other argument, it means that the termination is not successful. 

How to use sys.exit in Different IDE’S 

The output is different in different IDE’s. Except for string argument, the output for every other type of argument won’t work for Pycharm.  

But first, let us understand to use sys.exit with argument. 

Without Argument 

# Importing the sys module which contains exit function
import sys
# Runn the loop 10 times
for i in range(10):
    # Whenever we encounter '7' exit from the loop
    if i==7:
        sys.exit()
    print(i,end=" ")
python sys.exit

The output is different for different Integrated Development Environment(IDE).

For Jupyter Notebook,

 0 1 2 3 4 5 6

An exception has occurred, use %tb to see the full traceback. SystemExit

For PyCharm / IDLE,

0
1
2
3
4
5
6

Now let us learn how to use the arguments.

Using the string type argument

The output for string type argument remains mostly the same for all IDE’s.

import sys
# Create a function that will check whether a function is eligible to vote #or not 
def is_elegible(ages):
    # Iterating through all the ages
    for age in ages:
        if age<18:
            sys.exit("The minimum age for voting is 18")


ages=[19,27,88,12]
is_elegible(ages)
SystemExit: The minimum age for voting is 18

You can see that whatever we passed in the argument got printed after the SystemExit Exception.

Using the integer type argument

We can pass any integer we want. It can be status code too.

Jupyter Notebook,

attendees=["manoj","sara","sanjay","ashwini"]
if "ashwini" in attendees:
    sys.exit(0)
SystemExit: 0

In IDLE or Pycharm, the integer argument would not get printed.

import sys
def call_exit():
    for i in range(1,9):
        if i==7:
            print(sys.exit(1))
        print(i)
        
call_exit()
1
2
3
4
5
6

Using sys.exit along with Try block in python

We know that, if we are using try-except finally blocks, whatever we print in finally block gets printed for sure. Let us see whether it is true while using sys.exit or not.

for i in range(10):
    try:
    # if i==8, exit
        if i==8:
            
            sys.exit("We have encountered 8")
            
    except Exception as e:
        print("The value of was never 8")
    # Whatever happens, this will execute
    finally:
        print(i)   
0 1 2 3 4 5 6 7 8

An exception has occurred, use %tb to see the full traceback. SystemExit: We have encountered 8

Raising SystemExit Exception without using python sys.exit

Another way of exiting the program by raising the SystemExit exception is by using the raise keyword.

for i in range(10):
    if i==5:
        raise SystemExit("Encountered 5")
    print(i)
0 1 2 3 4

An exception has occurred, use %tb to see the full traceback. SystemExit: Encountered 5

It totally depends upon you, which way you want to exit the program. Everything else is the same about the two methods except that, for sys.exit, you have to import sys.

Comparing the sys.exit function with other functions in python

Two more ways are exit() and quit(). But they should not be used in the production environment because they use the site module which is not installed everywhere.

Another Common way for exiting is by using the os._exit(). So let us see what is the difference between the two.

os._exit() method is generally used to exit the process with a specified status without calling any cleanup handlers, flushing stdio buffers, etc. Also, it does not return anything.

Note: This method is normally used in the child process after the os.fork system call. Therefore, os._exit should only be used in some special scenarios.

So, the best way of exiting the program is sys.exit().

Conclusion

Whenever we want to exit from the program without reaching the end of the program, we can use the different exit programs available in python. The most standard and commonly used one is the sys.exit() function. We can also usu raise SystemExit to exit out of the program.

If you still have any problem or request, do let us know in the comment section below.

Happy Coding!

0 0 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kevin Wilson
Kevin Wilson
1 month ago

Check the code in “Using sys.exit along with Try block in python”

Maybe you should put the for loop inside the try block,
and maybe you should raise the error manually after the for loop?