How do I Terminate a Script in Python?

Terminating an interpreter kernel console means you want to get out of the execution process. Many programming languages offer shortcut keys and standard built-in functions to terminate a script. However, sometimes, upon executing a computationally expensive program, the interpreter gets stuck for any reason. In such scenarios, the user wants to eliminate such a situation by invoking a shortcut key combination or by pre-defining exit functions in their program. 

This article is about terminating a kernel console in Python. This article covers the following approaches to stop the execution process:

  1. Use the Try-Except Approach to Terminate a Kernel Console in Python
  2. Raising the KeyboardInterrupt to Stop a Script Execution in Python
  3. Use the “sys” Module to Stop a Script in Python
  4. Use the “os” module to Terminate a Kernel Console in Python

How to Terminate a Script in Python?

To terminate the script or stop the execution process, use the “quit()” or “exit()” function if working on Python IDE. However, if working on the latest iPython Interacting kernel then utilize the “os”, and sys” modules, or raise a “KeyboardInterruption” command to terminate a script. As the exit() and quit() do not properly work on the iPython kernels and may return the “NameError”:

“NameError: name 'quit' is not defined”

or 

“NameError: name 'exit' is not defined”

To successfully terminate a script in Python and their latest interacting IDEs, utilize the below set of approaches:

Approach 1: Use the Try-Except Approach to Terminate a Kernel Console in Python

The try-except block is utilized to terminate a script manually. In handling the error manually, the except block performs a considerable role. This property makes the try-except different from the if-else approach. Additionally, the execution time of the try-except is shorter than the if-else condition.  

To exit an interpreter console, follow the below example code for demonstration:

# Import the math module to perform a mathematical operation
import math 

try:
    # print the error when the number<0 
    print(math.sqrt(-1))
except:
    raise Exception("number should be non-negative")

The program in the try statement may raise the exception depending on the condition. If the error arises the except block will execute while terminating the script on printing the message provided within the “Exception()” braces.  

Output

Use the Try-Except with SystemExit to Terminate a Script in Python

Another prevalent approach to terminate a script is through the try-except statement by raising the “SystemExit()” function. It’s another approach to handle the error by raising the system exit within the except statement. Here’s how you can perform the system exit to terminate the script: 

# Import the math module to perform a mathematical operation
import math 

try:
    # print the error when the number<0 
    print(math.sqrt(-1))
except:
    raise SystemExit("number should be non-negative")

When the program catches the error, the “SystemExit()” terminates the script by raising and printing the message provided within its scope. 

Output

Approach 2: Raising the KeyboardInterrupt to Stop a Script Execution in Python

To terminate a script between execution the keyboard interrupt can be utilized. By pressing the correct key combination, the interpreter will consider it as a keyboard interrupt. To invoke a keyboard interrupt while executing, utilize the “CTRL+C” commands or particularly “Spyder IDE”, then you can use the “CTRL+SHIFT+F12” key combination to terminate a script. 

Here’s how you can raise a “KeyboardInterruption” command within the program to stop the execution process of the program: 

num=20
# Import the math module to perform a mathematical operation
import math 

while (True): 
    try:
    # print the error when the number<0 
        print(math.sqrt(num))
    # to handle the keyboard interruption
    except KeyboardInterrupt:
        print("number should be non-negative")
        raise SystemExit

Output

Approach 3: Use the “sys” Module to Stop a Script in Python

To terminate the execution process, use the “sys.exit()” function. The “sys.exit()” script termination method will terminate the execution process without raising any message unless you have manually provided it into the exit() function parentheses. To utilize the “sys.exit()” within the program, first, the “sys” module must be imported to the Python script. 

Here’s how you can utilize the “sys.exit()” method to terminate a script in Python: 

#consider importing the “time” module from “sleep” module
from time import sleep  

# importing sys
import sys

while (True): 
    time_delay=0.5
    print("\nstarts from now:\n")  
    print('its')
    sleep(time_delay)

    print('linux')
    sleep(time_delay)  
   
    print('foss')
    print("\n")
    sleep(time_delay)  
    sys.exit("\nTerminate upon successful printing with sys.exit()!")  

Output

Approach 4: Use the “os” module to Terminate a Kernel Console in Python

To terminate a script by intersecting with the operating system, use the “os._exit()” approach. The operating system utilizes its properties to exit the execution process. The exit(0) gives a command to the interpreter and system to exit the process without returning any message at the kernel console. In contrast, the exit(1) returns the message specified by the IDE. On Spyder IDE, it will restart the kernel and display the message on the kernel console. 

However, exit(0) and exit(1) may not function properly on various IDEs. In our case, on Spyder, the program exits and on termination returns, restarting the kernel console for both exit(0) and exit(1). 

Here’s how you can execute the os._exit() method while executing the program:

# importing sys
from sys import exit

#consider importing the “time” module from “sleep” module
from time import sleep  

# importing sys
import sys

while (True): 
    time_delay=0.5
    print("\nstarts from now:\n")  
    print('its')
    sleep(time_delay)

    print('linux')
    sleep(time_delay)  
   
    print('foss')
    print("\n")
    sleep(time_delay)  
    os._exit(0)
    print("\nTerminate upon successful printing with os._exit()!")

When the os._exit() method is invoked, it does not execute the code lines that come after it and terminates the script. 

Output

Bonus Tip: Using the “quit()” and “exit()” Functions to Exit a Python Script

To “quit()” and “exit()” functions are not proper functions of iPython interpreters. You need to consider importing the modules “from sys import exit” to use the exit() function in iPython (like Spyder IDE). 

The quit() and exit() functions properly on Python’s latest release IDE. However, to terminate the script by utilizing the quit() and exit() functions, hit the “Enter” to stop the execution process and shut down the IDE script. To learn more about using the exit commands in Python, go through our linked article “Exit Commands in Python”. 

That is all about terminating a script.

Conclusion

To terminate a script in Python, utilize the keyboard interruption command “CTRL+C” or any other system-specific key combination, or go with the try-except statement by raising the keyboard interruption in the “exception” code block. Users can also use the “os._exit()” function to exit the Python script by intersecting with the operating system. Moreover, the “sys.exit()” method can also be used to terminate the execution process on some readable message. This article has demonstrated the approaches to terminating a script in Python.