Clean up code when Ctrl+C is caught in python
Question: By registering the signal handler, I can put my clean up code in
signal_handler

    
    
    signal.signal(signal.SIGINT, signal_handler)
    

But the problem is when user presses ctrl+c multiple times, the signal handler
run multiple times and the clean up goes crazy.

**My problem is that, how can I make sure that the clean up handler is being
ran once only before exit.**

Here is my trial using lock, but deadlock is occured

    
    
    def cleanup_handler():
        lock.acquire()
        if not done:
            try:
                cleanup()
                done = True
            finally:
                print "release lock"
                lock.release()
    

The problem is that finally block is never ran (that is I can't see the
"release lock" being printed).

**Remark**  
After doing a little experiment, it seems that the signaler handler is not
being ran at the same time. When new Ctrl+C is received, the old handler is
killed and a new handler is ran. Am I correct? If yes, the problem becomes
more complicated as I don't want my handler ends in the middle of the....


Answer: You could use a decorator that prevents your function from being run more than
once:

    
    
    from functools import wraps
    
    def run_once(function):
        @wraps(function)
        def wrapper(*args):
            if not wrapper.has_run:
                wrapper.has_run = True
    
                return function()
    
        wrapper.has_run = False
    
        return wrapper
    

Like so:

    
    
    @run_once
    def signal_handler():
        print 'Exit'
    

