sir_ian
sir_ian

Reputation: 129

Nonfunctioning keyboard interrput

I have a python script with many problems, but the root cause of all of them is it wont react to the keyboard interrupt. I'm guessing the problem is either that I am using SSH only to connect or that I am using threads. Here it is as MCV as I could make it:

from threading import Thread           
import time, random                                                                                                                                             

def distance():                                                                                                                                                     
    while True:                                                                                                                                                         
        print "hi"                                                                                                                                              

def drive():                                                                                                                                                       
    while True:                                                                                                                                                         
        print "hi"                                                                                                                                               

distance = Thread(target=distance)                                                                                                                              
drive = Thread(target=drive)                                                                                                                                    
distance.start()                                                                                                                                                
drive.start()

If I stop it using kill PID it stops but I don't want to have to do that all the time.

Upvotes: 0

Views: 23

Answers (1)

John Zwinck
John Zwinck

Reputation: 249103

You can simply "unhook" SIGINT in Python so that it reverts to the default system behavior, which is to end the process:

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

Do that before starting your threads, and then Ctrl-C, rather than generating KeyboardInterrupt, will simply terminate the program.

Upvotes: 1

Related Questions