You can execute cleanup code if the interpreter exits: http://docs.python.org/lib/module-atexit.html
This will only cover the `Python's exit' part of your question, not the module reloading stuff. On the other hand, if you load a module you could set a global variable and check for it on reload... -- http://mail.python.org/mailman/listinfo/python-list