How to stop/terminate a python script from running?

There are several ways to stop a Python script from running:

  1. The most common way is to use the sys.exit() function. This function raises a SystemExit exception, which can be caught by a try-except block if needed, but will otherwise cause the script to terminate. For example:
import sys

# Some code goes here

sys.exit()

# The code below will not be executed

Watch a course Python - The Practical Guide

  1. Another option is to use the os._exit() function, which will cause the script to terminate immediately, without executing any pending cleanup handlers or flushing stdio buffers. This can be useful in situations where you need to terminate the script as quickly as possible. For example:
import os

# Some code goes here

os._exit(0)

# The code below will not be executed
  1. If you are running the script in a command prompt or terminal, you can use the CTRL-C key combination to stop the script. This will raise a KeyboardInterrupt exception, which you can catch in a try-except block if needed.

  2. If the script is running in an interactive interpreter (such as the Python shell), you can use the CTRL-D key combination to exit the interpreter and stop the script.

  3. Finally, if the script is running as a background process or daemon, you can use the kill command to stop it. For example, if the script is running as process 12345, you can use the command kill 12345 to stop it.