Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 995
pauliwago Avatar asked Mar 10 '13 02:03

pauliwago


People also ask

How do you capture CTRL C in Python?

You can handle CTRL + C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.

How do you use a signal handler in Python?

Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can't be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.

How do you handle Ctrl Z in Python?

Roughly speaking the Ctrl + Z from a Unix/Linux terminal in cooked or canonical modes will cause the terminal driver to generate a "suspend" signal to the foreground application. So you have two different overall approaches. Change the terminal settings or ignore the signal.

How do you catch SIGINT?

When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.


2 Answers

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.

like image 79
pradyunsg Avatar answered Oct 05 '22 04:10

pradyunsg


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) 
like image 32
abarnert Avatar answered Oct 05 '22 06:10

abarnert