pauliwago
pauliwago

Reputation: 6655

Capture Control-C in Python

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.

Upvotes: 57

Views: 104377

Answers (3)

rvcx
rvcx

Reputation: 59

As above, the standard approach is to catch KeyboardInterrupt. The one thing I'd add is that you probably shouldn't exit with code zero in this case, because you didn't complete processing. Honestly most callers care only about whether you return zero or nonzero, but in this case I'd do sys.exit(130), which means roughly "failed because I got a SIGINT".

Upvotes: -1

pradyunsg
pradyunsg

Reputation: 19406

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.

Upvotes: 94

abarnert
abarnert

Reputation: 365597

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)

Upvotes: 18

Related Questions