Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading