0

is there any way to catch an exception for an unexpected shutdown of program in python ?

let say I am running a python script in a console then I don't press control+c to stop the program but rather just click the close button of the console is there any way to catch the error before the console close?

like this:

try:
    print("hello")
except KeyboardInterrupt:
    exit()
except UnexpectedClose:
    print("unexpected shutoff")
    exit()

thanks in advance

8

1 Answer 1

0

Following the link I put in the comment above already and reading here that forced closing is sending a SIGHUP this modified version writes an output file when the terminal window is closed and the python process is "killed".

Note, I just combined information (as cited) available on SE.

import signal
import time

class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)
        signal.signal(signal.SIGHUP, self.exit_gracefully)

    def exit_gracefully(self,signum, frame):
        with open('kill.txt', 'w') as fpntr:
            fpntr.write('killed')
        self.kill_now = True

if __name__ == '__main__':
    killer = GracefulKiller()
    while True:
        time.sleep(1)
        print("doing something in a loop ...")
        if killer.kill_now:
            break
    print "End of the program. I was killed gracefully :)"

Not the answer you're looking for? Browse other questions tagged or ask your own question.