Используйте модуль atexit :
import mymodule
import atexit
# call mymodule.unload('param1', 'param2') when the interpreter exits:
atexit.register(mymodule.unload, 'param1', 'param2')
Другой простой пример из документов, использующий register
в качестве декоратора:
import atexit
@atexit.register
def goodbye():
print "You are now leaving the Python sector."