Difference Between exit() and sys.exit() in Python

[toc]

Problem: There are two similarly-named functions in Python, exit() and sys.exit(). What’s the difference between them, and when should I use one over the other?

Introduction

In contrast to programming languages like C, there is no main() method in Python. Thus, when we run a program in Python, we essentially execute all the code in the top-level file, i.e., from top to bottom. The scripts typically exit themselves when Python tumbles off the end of the document, yet we can likewise call for program exit unequivocally with the help of exit commands. In this tutorial, we will learn about two different exit commands in Python – exit() and sys.exit(). We will also learn the difference between exit() and sys.exit().

? When and why do we need the exit() commands in Python?

When you implement a program in Python, the code is executed consecutively until the end. However, there can be occasions when we require the program to end sooner than anticipated. This is where different exit commands come into the picture.

Although Python is a simple programming language, sometimes it might get a little complex. One such case is the utilization of different sorts of exit commands in Python.

β›” exit() | Python

The exit() will straightforwardly end the execution of the Python code/script. The code that follows thereafter the exit() command won’t be executed.

Note:

  • You can think of exit() as an alias for quit() (or vice-versa) in Python. They simply co-exist to make Python more user-friendly. However, it is not a good practice to use quit() and exit() in production code and should only be reserved for use in the interpreter.
  • exit() command generates the following message when printed:
    • Use exit() or Ctrl-D (i.e. EOF) to exit
  • βž₯ Example:
for no in range(15, 30):
    if no > 25:
        print("\n", exit)  # printing the exit message
        # When the value of no becomes 10 then the program is forced to exit
        exit()
    print(no, end=" ")

Output:

15 16 17 18 19 20 21 22 23 24 25 
 Use exit() or Ctrl-Z plus Return to exit

Explanation: As soon as no is greater than 25, the exit() method is executed, and the program terminates after printing the exit message.

β›” sys.exit() | Python

You can call the sys.exit() to exit from the Python code with exit status as arg. The arg (argument) can be anything like an integer or another object-the arg defaults to zero, which indicates successful termination. You can set arg to a non-zero value to denote an abnormal termination of the code.

#Trivia:

  • When we use the sys.exit() command, it raises the built-in SystemExit Exception. Along these lines, you can catch it as usual to block early exits and perform cleanup activities when necessary.
  • sys.exit(s) can be considered just as a shorthand for raise SystemExit(s)
import sys
try:
    sys.exit()
    print("This Line won't be Executed!")
except SystemExit:
    print("SystemExit Exception terminated the program!")
finally:
    print("Perform Cleanup Activities!")

Output:

SystemExit Exception terminated the program!
Perform Cleanup Activities!

Now, let us have a look at an example to get hold of the sys.exit() method in Python.

βž₯ Example:

import sys
num = int(input("Enter a number: "))
if num < 20:
    # exits the program
    sys.exit("Exiting! The number is less than 20.")
else:
    print("Number = ", num)

Output:

Enter a number: 5
Exiting! The number is less than 20.

Explanation: As soon as the user input is less than 20, the sys.exit() command gets executed, which prints the arg as exit status, i.e., “Exiting! The number is less than 20.

✨ Difference Between exit() and sys.exit()

exit()sys.exit()
βž₯ Should not be used while dealing with production code.
βž₯ It can be used within an interpreter.  
βž₯ sys.exit() is a good option if you are dealing with production code.  
βž₯ exit() belongs to the site.py module and works only if the site module is imported/present.
βž₯ The site module is automatically imported during start-up, except if the -S command-line option is used.
βž₯ sys module is always available, which makes sys.exit() a better and convenient option.

Now, let us have a look at an example that will clarify things further.

βž₯ Example

In the following example, you will come across a couple of functions:

  • foo() – used to demonstrate the working principle of sys.exit()
  • func() – used to demonstrate the working principle of exit()
import sys


def foo():
    try:
        print("Demonstrating sys.exit()")
        sys.exit()
        print("This line will not be executed!")
    except SystemExit:
        # argument denoting exit status
        print("Abnormal Termination! Encountered SystemExit")


def func():
    print("Demonstrating exit()")
    print(exit)
    exit()  # lines after this statement are ignored and are not executed
    print("The previous command executes ignoring all the lines after the command")


# Calling both the function:
foo()
print()
func()

Output:

Demonstrating sys.exit()
Abnormal Termination! Encountered SystemExit

Demonstrating exit()
Use exit() or Ctrl-Z plus Return to exit

Explanation:

  • Inside foo(), line 8 is ignored because Python encountered the sys.exit(). As a result the control moved on to the except block and the custom error message was displayed.
  • Inside func(), line 18 was not executed since Python encountered the exit() method and the program was terminated.

? A Commonly Asked Question: Difference between exit(0) and exit(1) in Python?

exit(0) denotes a successful exit of the program/script without the occurrence of any errors/problems, i.e.; it signifies successful execution. In contrast, a non-zero exit like exit(1) denotes an abnormal termination of the code. At times, error codes can also signify the type of problem encountered, which leads to the abrupt termination of the script.

Conclusion

To summarize this discussion, you should remember that sys.exit() is more elegant, and a SystemExit Exception will be thrown after the call. The exit() command abruptly terminates the Python script, and the rest of the statements are not executed.

? Read Here: How to Fix TypeError: Can’t Multiply Sequence by non-int of Type β€˜float’ In Python?

I hope this article helped you to understand the difference between sys.exit() and exit() in Python. Please subscribe and stay tuned for more interesting tutorials. Happy learning! ?

Thank you Rashi Agarwal for helping me with the article!

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!