40

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.

pauliwago
  • 5,883
  • 11
  • 37
  • 50
  • 2
    Something like this: http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python? – A. Rodas Mar 10 '13 at 02:24
  • 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 Mar 10 '13 at 02:25
  • 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 Mar 10 '13 at 02:36
  • @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 Mar 10 '13 at 02:37
  • 3
    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 Mar 10 '13 at 02:39
  • As a side note: You shouldn't call a variable `input`, because that shadows the builtin function of the same name. – abarnert Mar 10 '13 at 02:40
  • I don't think this was a dup. If I understand the OP's problem, it's not catching the Ctrl-C that's a problem, but quitting (without a backtrace) when he catches it. Switching from `KeyboardException` to a SIGINT handler isn't the answer. It solves some _other_ problems he might have—and also creates some _new_ problems. But mainly, it leaves his existing problem exactly the same. – abarnert Mar 10 '13 at 22:30

2 Answers2

67

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.

pradyunsg
  • 16,339
  • 10
  • 39
  • 91
  • `site.exit` (builtins exit) won't be defined if Python is started with `-S`. That isn't common, but still, `sys.exit` is more dependable. You can also use `raise SystemExit([exit_code=0])`. – Eryk Sun Mar 10 '13 at 09:04
15

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)
abarnert
  • 334,953
  • 41
  • 559
  • 636