I would like to know if there is a way of programatically stopping a python script execution without killing the process like we do with this code:
import sys
sys.exit()
It would be the code equivalent to Ctrl+c
Using KeyboardInterrupt If you want to exit the running program, then you need to raise a KeyboardInterrupt to terminate it. For Windows, press CTRL + C. If the KeyboardInterrupt does not work, then you can send a SIGBREAK signal. On Windows, press CTRL + Pause/Break.
Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.
_exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in the child process after os. fork() system call. The standard way to exit the process is sys. exit(n) method.
Define your own exception,
class HaltException(Exception): pass
and wrap the script in
try:
# script goes here
# when you want to stop,
raise HaltException("Somebody stop me!")
except HaltException as h:
print(h)
# now what?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With