Search code examples
pythonloggingtermination

Run a function at forceful termination of the script in Python


I have created a log and want it to be updated at forceful termination of the python script. This will help in keeping a track of all the forceful terminations. I tried , but atexit() runs only on normal termination.


Solution

  • Just catch the KeyboardInterrupt exception.

    This simple program demonstrates how a function can be run when the Ctrl+C key combination is pressed to exit.

    def main():
        while True:
            input('')
    
    def onexit():
        print('on exit')
    
    try:
        main()
    except KeyboardInterrupt:
        onexit()