Santi Peñate-Vera Santi Peñate-Vera - 3 months ago 8
Python Question

Stop python script without killing the python process

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

Answer

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?