I am using Python's default cmd module to create a command-line-based app.
According to the docs CTRL+D (which signals EOF to the command line) can be captured by implementing a function called do_EOF, which works pretty well.
However, is there a way to capture CTRL+C as well? I want to execute a specific function (which saves all unsaved changes) before terminating the Python-script, which is the main motivation for doing this.
Currently, I capture KeyboardInterrupts using a try-except-block like the following:
if __name__ == '__main__':
    try:
        MyCmd().cmdloop()
    except KeyboardInterrupt:
        print('\n')
I tried to extend this into:
if __name__ == '__main__':
    try:
        app = MyCmd().cmdloop()
    except KeyboardInterrupt:
        app.execute_before_quit()
        print('\n')
Which leads to the following NameError:
name 'app' is not defined
How can I capture CTRL+C?
I think signal could somehow do the trick, but I am not sure...
Remark: The script needs to be running on both Unix- and Windows-based systems.
 
    