Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a Python module unloads

Tags:

python

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?

like image 796
iconoplast Avatar asked Feb 20 '09 18:02

iconoplast


1 Answers

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."
like image 131
nosklo Avatar answered Oct 21 '22 16:10

nosklo