Python: Check if Program is being closed

Viewed 2875

all.

Is there a way, using Python, to check if the script that is currently running is requested to close? For example, If I press the X-Button (close program button) on the top-right to close it, or end the script in any other way, can the script do some code before it ends? Example:

# script goes here...

if Script_To_Be_Closed: # replace this with an actual line of code.
    do_stuff
2 Answers

There are multiple options you may use, like trapping keyboardinterrupts, but the simplest is atexit, which executes a function whenever a scripts is ended (except of a hard process kill indeed).

import atexit

def my_exit_function(some_argument):
    // Your exit code goes here
    print(some_argument)


if __name__ == '__main__':
    atexit.register(my_exit_function, 'some argument', )

    // Your script goes here

You can use a shell script to do the job

You can see the script command shown below which calls itself after executing the command to run the python file. once the python file is closed the next line will force the python command to run again. you can also customise the behaviour the way you want.

main.py

#!/bin/bash
python3 ./main.py
source ./infiniteRun.sh

If you need to stop the job just edit the file and remove the last line source ./infiniteRun.sh and save the file.

Related