How to to do something before the blender game engine ends with a script
You can use an app event handler for this.

An event handler is a function (known as a "callback") that is launched when the event is triggered. You can append a custom function of your own to blender's event handlers, and it will be launched when these events are fired.

Conveniently, there's such an event for the end of the game engine (bpy.app.handlers.game_post).

import bpy

def execute_after_game( scene ):
    print( "GAME OVER!!" )

bpy.app.handlers.game_post.append( execute_after_game )


This example will add a function that prints "GAME OVER!!" to the terminal after the game is finished.