I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the library that I'd like to be called. How can I create this hook?
+7
A:
Use the atexit module:
import mymodule
import atexit
# call mymodule.unload('param1', 'param2') when the interpreter exits:
atexit.register(mymodule.unload, 'param1', 'param2')
Another simple example from the docs, using register
as a decorator:
import atexit
@atexit.register
def goodbye():
print "You are now leaving the Python sector."
nosklo
2009-02-20 18:19:37
atexit can be an inconvenient/unclean solution(?), especially if the process forks etc. Maybe it's better to just skip the magic and provide a "cleanup"/finalization function that the module user should call?
kaizer.se
2010-05-12 08:20:39
if you `fork`ed you want to cleanup the child process too, since it will share all memory structures.
nosklo
2010-05-12 12:00:17