5

Is it possible to get a callback before Blender closes?

There are bpy.app.handlers. Unfortunately there is no handler for closing Blender.

So is there a way to to know in a script when blender is about to close?

ideasman42
  • 47,387
  • 10
  • 141
  • 223
ndee
  • 658
  • 5
  • 15

1 Answers1

5

While we could support this via bpy.app.handlers, we decided not to add this since Python already supports exit callbacks, so you can use these (outside of Blender too - for any Python script).

See Python's atexit module.

Simple example use:

def goodbye(name, adjective):
    print("Goodbye, %s, it was %s to meet you." % (name, adjective))

import atexit atexit.register(goodbye, "Suzanne", "nice")

Note : To unregister the callback when disabling an add-on for instance, you can use :

atexit.unregister(callback)
Gorgious
  • 30,723
  • 2
  • 44
  • 101
ideasman42
  • 47,387
  • 10
  • 141
  • 223
  • ok. This works. But I have a problem with it. When running the script from blender this function gets registered. But when putting it into an addon I get this error: Error: EXCEPTION_ACCESS_VIOLATION – ndee Mar 10 '16 at 10:21
  • Try find which line causes the error, This will run when Blender is shutting down - so its possible you access data which is already freed. – ideasman42 Mar 10 '16 at 10:25
  • 2
    I know this post is very old, but I wanted to add information in case anyone finds this post because of the same problem. If you try to access your add-on's preferences during this event, you will get an access violation error. I was able to access several things from Blender, but not my own addon's preferences. In my opinion, Blender should notify add-ons of a shutdown BEFORE any data is released. – Robert Nov 11 '19 at 12:18
  • where do you use atexit.register? i tried placing it in the add-on def register but it doesn't seem to work – mayotic Jun 06 '20 at 17:56