Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check if Program is being closed

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
like image 510
ShakeyGames Avatar asked Oct 30 '25 05:10

ShakeyGames


1 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
like image 121
Orsiris de Jong Avatar answered Nov 01 '25 18:11

Orsiris de Jong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!