Is there any way to detect when a python program will end?

Is there any way to detect when a python program will end? Something like a callback I can connect to?

I have a class that saves cache , and I would like to write the cache to disk before the program terminates. If I can do this, I can load it from disk on first use and have a persistent cache.

I am looking for a type of callback type, although I want to automate it, so the user does not need to do anything to save the cache.

+4
source share
2 answers

You can use atexit.register(some_function) or just decorate your function with @atexit.register . It will be called when the interpreter completes.

Example:

 import atexit @atexit.register def save_cache(): print 'save cache' 

or

 import atexit def save_cache(): print 'save cache' atexit.register(save_cache) 
+7
source

Yes there are :

 import atexit @atexit.register def writecache(): # etc 
+7
source

Source: https://habr.com/ru/post/1441931/


All Articles