How to Exit a Python Program in the Terminal

This article covers the most essential and frequently used Python exit functions that enable you to exit a Python program. Python is a versatile language suitable for a wide range of tasks, but there are instances when you need to exit a script systematically So, let’s dive into the article!

There are several methods to exit a Python program in the terminal. The simplest approach involves using the Python shell and entering the following commands at the end of your code to gracefully exit the Python shell:

  • quit() function
  • exit() function
  • sys.exit()
  • os._exit()
  • raise SystemExit

These commands facilitate a smooth exit from a Python program, allowing you to close the program, clean up resources, and signal to Python that the process is complete. These commands serve different purposes for exiting your code at various stages of the program, upon completion, or when you wish to halt it. Lets discuss them one by one in detail.

Terminating a Python program with quit()

The built-in quit() function is used to close and terminate the current Python script. When quit() is invoked, it promptly terminates the script and exits the Python environment without generating any output.

Open the Command Prompt, type python and press Enter. This will open the Python interpreter, allowing you to execute Python commands. You can enter and execute any Python commands or scripts inside this interpreter.

C:\Users\User>python
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("there")
there

To stop the current python program, press quit() command. This command will terminate the Python session and close the interpreter.

>>> quit()

C:\Users\User>

You can also use the quit() command when you want to terminate a script under specific conditions or when certain criteria are met. The most common example is when you want to continue or exit a program based on user’s input.

# Get user input
response = input("Do you want to continue (yes/no)? ")

# Check if the user wants to continue
if response.lower() == 'no':

    print("Exiting the program...")
    
    # Terminate the program
    quit()  


# If the user wants to continue, perform some other tasks
print("Continuing with the program...")

Output:

Do you want to continue (yes/no)? yes 
Continuing with the program...

In this example, the script asks the user whether they want to continue. If the user enters ‘no’, the script prints an exit message and then uses the quit() command to terminate the program gracefully. If the user enters ‘yes’, the script continues with its tasks.

However, an important consideration is that if the print() statement comes after quit(), the message will be printed before exiting the program. However, if print() is positioned before or above quit(), the program will still exit, but it won’t have any impact on the message within the program body. This detail is crucial for controlling the output when using quit() in Python scripts.

Keep in mind that using quit() within a script is just one way to control program flow. Depending on your script’s complexity and requirements, you may use other control flow structures, like if-else statements or exceptions, to achieve similar results.

exit() Function to exit a Python program

Another way is to use exit() function to exit a Python program. It is often used in interactive environments like Python’s REPL (Read-Eval-Print Loop) to terminate the interpreter session.

C:\Users\User>python
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World!")
Hello World!
>>> print(2+3)
5
>>> print(2*5)
10
>>> exit("terminate the program")
terminate the program

C:\Users\User>

It is recommended to use exit only in interpreters, not in the program. You can also pass an integer as an argument in the exit() function. If ‘0’ is passed, the program displays success message. On the other hand, any non-zero integer indicates failure or program termination. Because exit() is defined in the site module, and it only works when the site module is imported, that’s why it should only be used in the interpreter. 

Furthermore, if the Python interpreter encounters an abrupt termination or stoppage, it may display a message or warning related to the exit() function, such as “Use quit() or Ctrl-D to exit.” This message serves as a reminder to utilize the quit() function or Ctrl-D command for a more controlled and expected program exit.

Using sys.exit() to Terminate a Python Script

Another method to terminate a script programmatically involves the use of sys.exit() function. It serves the same purpose as quit() and exit(), providing a convenient way to terminate the program. The sys.exit() command is an in-built function used to exit the program. When invoked, it raises the SystemExit exception.

Lets understand it through an example:

import sys

# List of URL components
url = ['www.', 'Entechin', '.com', 'stop']

# Start a loop as long as there are items in the 'url' list
while url:
    # Remove and assign the first item from the 'url' list to 'site'
    site = url.pop(0)
    
    # Check if 'site' is 'stop'
    if site == 'stop':
        # If 'site' is 'stop', exit the loop
        break
    
    #This will exit the program
    sys.exit() 

Output:

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

SystemExit
/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py:3561: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

In the above example, the code processes a list called ‘url’ containing URL components. It iterates through the list, and when it encounters the string ‘stop’, it exits the loop and the program using sys.exit(). Any code after this point won’t execute.

You can also pass an argument within the exit() function to indicate successful termination. It can be an integer or a string. When the function is invoked, the program terminates with a SystemExit exception, and the integer or string message gets printed ion the output window.

import sys

# Define a list of URL components
url = ['www.', 'Entechin', '.com', 'stop']

# Iterate through the list
while url:
    # Get the first element from the list
    site = url.pop(0)

    # Check if the element is 'stop'
    if site == 'stop':
        # If 'stop' is encountered, exit the loop
        break

    # Display a termination message and exit the program
    sys.exit("Program Successfully Terminated!....")

Output:

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

SystemExit: Program Successfully Terminated!....

Unlike quit() and exit() commands, the sys.exit() function can be used in production code. It is typically recommended for use in programs. Please note that the sys.exit() function will exit the entire Python program, so any code after it in this script will not execute.

Using os._exit() to Terminate a Python Program from the Command Line

The os._exit() is a more abrupt exit. It immediately terminates the program without raising any exception and performing any cleanup operations as in exit() method. It is mostly used in situations where you need to forcibly end the program. To use this function, import the ‘os’ module first. Then using dot operator, you can call the _exit() function. The os._exit(n) function takes ‘n’ argument which is an integer value. This argument represents the exit code.

Consider the following example:

# Importing os module
import os

# Inserts program Logic

# Using os._exit() to terminate script
os._exit(0)

The argument ‘0’ in os._exit() indicates the exit status of program. Typically, a non-zero exit status denotes an error or an aberrant termination, while an exit status of 0 denotes a successful or normal termination.

raise SystemExit to come out of Python Script

Similar to how the sys.exit() function programmatically raises the SystemExit exception from within your code, you can also raise the SystemExit exception using the built-in Python exception class designed to represent a request to exit the program. This exception can optionally take an argument.

If no argument is provided, the exception returns the error message ‘An exception has occurred, use %tb to see the full traceback.’ However, if a string (which can be a custom terminating program message) is passed as an argument to the SystemExit exception, it will return that string along with the above-mentioned error message.

import time

# List of websites
websites = ['www.google.com', 'www.facebook.com', 'www.example.com', 'www.python.org', 'www.stopcrawler.com']

for site in websites:
    print(f"Crawling website: {site}")
    time.sleep(1)  # Simulate crawling by sleeping for 1 second
    
    if site == 'www.stopcrawler.com':
        print(f"Stopping crawler at website: {site}")
        raise SystemExit('Crawler terminated successfully')

Output:

Crawling website: www.google.com
Crawling website: www.facebook.com
Crawling website: www.example.com
Crawling website: www.python.org
Crawling website: www.stopcrawler.com
Stopping crawler at website: www.stopcrawler.com
An exception has occurred, use %tb to see the full traceback.

SystemExit: Crawler terminated successfully

In this code, we start a web crawler that iterates through a list of websites. It simulates crawling by printing the name of each website and sleeping for 1 second. When it encounters ‘www.stopcrawler.com‘, it stops the crawler and raises SystemExit with a termination message.

Conclusion

In this article, we’ve explored five different methods to gracefully terminate, abort, or exit a Python program, each with its own unique use cases. The exit() and quit() functions are typically used within the Python interpreter when working with smaller scripts or interactive sessions. However, when dealing with larger Python files or scripts, it’s advisable to employ sys.exit() and os._exit(), which provide more control over program termination. The choice between exit() or quit() and sys.exit() or os._exit() depends on the specific requirements of your problem.

To learn more about Python Programming, visit Python Programming Articles.

Leave a Comment

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