pythonpycharmsaveexecutiontermination

Trigger action when manually stopping Python script


I was searching for quite some time but I was unable to find a simple solution. I have a python script that runs indefinitely and saves some files when a condition is met (enough data gathered). Is there a way to terminate the execution of the script and trigger a function that would save the gathered (but yet unsaved) data? Every time I have to do something (let's say close the computer), I must manually stop (terminate) script (in Pycharm) and I loose a part of the data which is not yet saved.

Edit: Thanks to @Alexander, I was able to solve this. A simple code that might better outline the solution:

import atexit
import time

@atexit.register
def on_close():
    print('success') #save my data

while True:
    print('a') 
    time.sleep(2)

Now when clicking on a Stop button, 'on_close' function is executed and I am able to save my data...


Solution

  • Use the atexit module. It part of the python std lib.

    import atexit
    
    @atexit.register
    def on_close():
        ... do comething
    

    atexit.register(func, *args, **kwargs)

    Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once.

    This function returns func, which makes it possible to use it as a decorator.