How to stop/terminate a python script from running?
There are several ways to stop a Python script from running:
- The most common way is to use the
sys.exit()
function. This function raises aSystemExit
exception, which can be caught by atry-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 video course
Python - The Practical Guide
- 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
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 aKeyboardInterrupt
exception, which you can catch in atry-except
block if needed.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.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 commandkill 12345
to stop it.