Saving work after a SIGINT
Question: I have a program which takes a long time to complete. I would like it to be
able to catch `SIGINT` (ctrl-c) and call the `self.save_work()` method.

As it stands, my `signal_hander()` does not work since `self` is not defined
by the time the program reaches `signal_handler()`.

How can I set it up so `self.save_work` gets called after a `SIGINT`?

    
    
    #!/usr/bin/env python
    import signal 
    
    def signal_handler(signal, frame):    
        self.save_work()   # Does not work
        exit(1)
    signal.signal(signal.SIGINT, signal_handler)
    
    class Main(object):
        def do_stuff(self):
            ...
        def save_work(self):
            ...
        def __init__(self):
            self.do_stuff()
            self.save_work()
    
    if __name__=='__main__':
        Main()
    


Answer: If you just want to catch ctr+c then you can catch the
[KeyboardInterrupt](http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt)
exception:

    
    
    class Main(object):
        def do_stuff(self):
            ...
        def save_work(self):
            ...
        def __init__(self):
            try:
                self.do_stuff()
            except KeyboardInterrupt:
                pass # Or print helpful info
            self.save_work()
    

Not that I think this is a good design after all. It looks like you need to be
using a function instead of a constructor.

