I want to do something before the blender game engine stops. For example, print "THE END" on terminal when I press ESC to exit (scripting).
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).
This example will add a function that prints "GAME OVER!!" to the terminal after the game is finished.
When does your game end?
It ends when you either press ESC (default setting), or you activate the Game Actuator.
The default setting does not let you much choice as you can't "intercept" the end of the game.
But, you can override the default.
Attention: be very careful with the next steps. Otherwise it is possible you can't stop your game anymore.
Therefore we first completely override the exit behavior with our own one.
Please do it exactly that way.
When you setup ESC in any keyboard sensor the default exit will be disabled. Therefore you have to setup a custom exit (game actuator).
With that you know when the game ends as you sense the request for ending the game (pressing ESC).
Your requirement was
So you can trigger a Python controller with the same keyboard sensor. (Do not replace or disconnect the AND Controller - most-likely you forget to activate the connected actuators from your Python controller)
Be aware actuators will not show any effect as the game ends within the next frame.