4

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.

Community
  • 1
  • 1
Justin808
  • 20,859
  • 46
  • 160
  • 265

2 Answers2

8

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)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
7

Yes, there is:

import atexit

@atexit.register
def writecache():
    # etc
Eric
  • 95,302
  • 53
  • 242
  • 374