Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect when a python program is going to end?

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.

like image 562
Justin808 Avatar asked Dec 07 '22 11:12

Justin808


1 Answers

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)
like image 106
ThiefMaster Avatar answered Jan 22 '23 16:01

ThiefMaster