How to run script on exit

I need to run a clean up method when the blender game engine exits, but I’m not exactly sure how to do this :(. Any help is appreciated.

If you set a sensor to look for the esc key, it will remove the game engine’s default esc key behavior- that way you can have it run a script and then exit, rather than exiting immediately. Just link the script to a keyboard sensor set to esc, and at the end of the script have it activate an end game actuator.

Careful though, if the script crashes the game won’t exit and you’ll have to force quit blender. Make sure you debug the script before you rely on it.

Add a keyboard sensor to any object, that reacts on the “esc”-key. This way the game won’t quit on press of the escape key. Now you can runn your clean up. After that make the game quit by calling a game actuator set to “quit game”.

Thanks for the replies, but how would I do this blender 2.5? If I try to set a keyboard sensor to the esc key blender doesn’t accept it. I can probably do this through python, but I would have to know the number that blender assigned the esc key, and I don’t.

own = GameLogic.getCurrentController().owner
escape = own.sensors['key']
escape.key = ??

Any ideas?

Edit –

I looked through the source code for Blender and found out that the key code for escape is 130. Unfortunately when I set the key to this I get no effect. Does Blender 2.5 just exit on escape before python gets to read the key input, and if it does, is there anything to do to stop this?