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 aSystemExitexception, which can be caught by atry-exceptblock 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- 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 executedIf you are running the script in a command prompt or terminal, you can use the
CTRL-Ckey combination to stop the script. This will raise aKeyboardInterruptexception, which you can catch in atry-exceptblock if needed.If the script is running in an interactive interpreter (such as the Python shell), you can use the
CTRL-Dkey 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
killcommand to stop it. For example, if the script is running as process 12345, you can use the commandkill 12345to stop it.