37
votes

I want to know if it's possible to catch a Control-C in python in the following manner:

 if input != contr-c:
    #DO THINGS
 else:
    #quit

I've read up on stuff with try and except KeyboardInterrupt but they're not working for me.

2
Yes, but I've tried using KeyboardInterrupt but instead of just exiting, Python does the operations in try, which is not what I want. - pauliwago
What platform are you on? And what version of Python? And are you reading input via input/stdin.read/etc., a platform-specific getch (if so, which?), curses, or …? It's generally possible in every case, but the answers are very different between the cases. - abarnert
@pauliwago: What do you mean "Python does the operations in try"? Normally, when you handle an exception, Python does the operations in the except block. If you want it to quit, you can just, e.g., call sys.exit() in that except block. - abarnert
And more generally: Just saying "not working for me" isn't very useful. Tell us exactly what you tried, what you expected, and what happened instead. - abarnert

2 Answers

61
votes

Consider reading this page about handling exceptions.. It should help.

As @abarnert has said, do sys.exit() after except KeyboardInterrupt:.

Something like

try:
    # DO THINGS
except KeyboardInterrupt:
    # quit
    sys.exit()

You can also use the built in exit() function, but as @eryksun pointed out, sys.exit is more reliable.

12
votes

From your comments, it sounds like your only problem with except KeyboardInterrupt: is that you don't know how to make it exit when you get that interrupt.

If so, that's simple:

import sys

try:
    user_input = input()
except KeyboardInterrupt:
    sys.exit(0)