How To Exit Python Script In Terminal

In this tutorial, we will guide you on how to exit a Python script running in the terminal. Exiting a Python script can be helpful if you need to halt the execution of a script or gracefully close down a script’s functions. We’ll go through several methods of exiting a Python script that suits various scenarios.

Method 1: KeyboardInterrupt – Using Ctrl+C

The most common method to exit a Python script running in a terminal is to issue a KeyboardInterrupt by pressing the CTRL+C keys simultaneously. When the script is running, press CTRL+C, and it will raise a KeyboardInterrupt exception, causing the script to terminate.

Output:

Method 2: Using sys.exit()

Another method to exit a Python script is to use the sys.exit() function provided by the sys module. This function raises a SystemExit exception, and the script will terminate cleanly.

  1. First, import the sys module by adding the following line to the top of your script:
  1. Then, add the following line where you want the script to exit:

Output:

Method 3: Using os._exit()

In situations where you need to force an immediate exit, you can use the os._exit() function provided by the os module.

This function does not raise any exceptions and terminates the script immediately, which can be useful in situations where the script might be stuck in an infinite loop.

  1. First, import the os module by adding the following line to the top of your script:
  1. Then, add the following line where you want the script to exit:

The _exit() function requires an exit_code as an argument. The exit_code is an integer value that indicates the reason for exiting the script. A value of 0 indicates a successful exit, while any other value indicates an error.

Output:

Conclusion

In this tutorial, we covered three different methods to exit a Python script running in the terminal:

  1. KeyboardInterrupt – Using Ctrl+C
  2. Using sys.exit()
  3. Using os._exit()

Each of these methods serves its purpose depending on the specific scenario or outcome you need. Choose the suitable method for your script according to your requirements and use it to gracefully exit your Python scripts.