Is there a way to detect when a python program is going to end? Something like a callback I can connect to?
I have a class thats keeping a cache and I'd like to write the cache out to disk before the program ends. If I can do that then I can load it up from disk the first time its used and have a persistent cache.
I'm looking for a callback type thing though cause I want to automate it so the user doesn't have to do anything to have the cache saved.
You can use atexit.register(some_function)
or simply decorate your function with @atexit.register
. It will be called when the interpreter terminates.
Example:
import atexit
@atexit.register
def save_cache():
print 'save cache'
or
import atexit
def save_cache():
print 'save cache'
atexit.register(save_cache)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With