1

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.

albert
  • 8,027
  • 10
  • 48
  • 84
  • 2
    Have you considered using `atexit` instead? https://docs.python.org/3/library/atexit.html – cdarke Jun 26 '15 at 12:52

1 Answers1

0

Ctrl C activates system exit which is like an exception, I'm pretty sure you can catch it with try and except. Note: to catch SystemExit you must specify it in the except explicitly.

Idan Dor
  • 116
  • 9