Skip to main content
How Can I Exit Python Using the Command Line

How Can I Exit Python Using the Command Line?

in this tutorial, We’ll learn about different ways to gracefully exit a from python program. You can exit by using methods such as the quit(), exit(), and sys.exit() commands.

We’ll discuss the following method here:

  • Exit using quit().
  • Exit using exit().
  • Exit using sys.exit().

Python quit() function

The quit is a built-in python method that is used to exit from a Python program. it terminates the execution of the program completely. It stops the interpreter and returns to the operating system.

for val in range(0,10):
 if val == 3:
 quit()
 print(val)

in the above code, We are printing “val”, if the value of “val” becomes "3" then the program is forced to quit, and exit from program.

Python exit() function

The exit is a built-in Python method that is used to exit and come out of the program in Python. it’s functionality is the same as quit() method exit from the program.

for val in range(0,10):
 if val == 3:
 exit()
 print(val)

in the above code, We are printing “val”, if the value of “val” variable value is "3" then the program is forced to quit, and exit from program.

Python sys.exit() function

The sys.exit() method is part of the sys module. This method terminates Python program execution instantly. It raises the SystemExit exception and returns exit code, The exit code 0 for successful execution and non-zero values for errors.

import sys

def main():
    try:
        # Program logic
        result = 5 / 0
    except ZeroDivisionError as e:
        print(f"Error: {e}")
        # Exit with status code 1 for division by zero
        sys.exit(1)

if __name__ == "__main__":
    main()
    # Exit with status code 0 for successful execution
    sys.exit(0)

Python atexit Module:

Python’s atexit module enables programmers to register functions that run right before a program ends. This can be helpful for cleaning up after operations.

import sys
import atexit

def cleanup():
    # Cleanup operations
    print("Performing cleanup before exit.")

atexit.register(cleanup)

# Program logic here
sys.exit(0)

Conclusion

We learned common ways to terminate Python program execution. The Python exit commands – quit(), exit(), and sys.exit(), These methods allow the termination of Python script execution gracefully. You can choose any of them as per your needs.

Leave a Reply

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