1

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...

Matija Cerne
  • 127
  • 1
  • 9

1 Answers1

1

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.

Alexander
  • 16,091
  • 5
  • 13
  • 29
  • 1
    Thank you very much, I think this is exactly what I was looking for... I made a simple code just to test how it works, and it worked just fine: import atexit import time @atexit.register def on_close(): print('success') while True: print('a') time.sleep(2) – Matija Cerne Oct 01 '22 at 22:32
  • 1
    @MatijaCerne Terrific glad I could help – Alexander Oct 01 '22 at 22:34
  • do you maybe have an idea how would it be possible to make atexit work also when there is apparently an 'unclean' exit: "Process finished with exit code -1"? I am running two while loops simmultaneously and for some reason I am unable to stop the execution by only clicking 'Stop' button once - I must hit it once and then again, which I think kills the process... – Matija Cerne Oct 01 '22 at 23:55
  • 1
    You just need to make sure you catch any Exceptions that occur and then exit gracefully. But you are better off refactoring your code so that it exits gracefully on it's own. It's bad practice to have to force kill a process in order to make it stop. @MatijaCerne – Alexander Oct 02 '22 at 00:42
  • Ok, I see, thank you.. I'll use try catch. Thank you for pointing me in this direction! – Matija Cerne Oct 03 '22 at 14:58