Fix Python – Cannot kill Python script with Ctrl-C


Asked By – dotancohen

I am testing Python threading with the following script:

import threading

class FirstThread (threading.Thread):
    def run (self):
        while True:
            print 'first'

class SecondThread (threading.Thread):
    def run (self):
        while True:
            print 'second'


This is running in Python 2.7 on Kubuntu 11.10. Ctrl+C will not kill it. I also tried adding a handler for system signals, but that did not help:

import signal 
import sys
def signal_handler(signal, frame):
signal.signal(signal.SIGINT, signal_handler)

To kill the process I am killing it by PID after sending the program to the background with Ctrl+Z, which isn’t being ignored. Why is Ctrl+C being ignored so persistently? How can I resolve this?

Now we will see solution for issue: Cannot kill Python script with Ctrl-C


Ctrl+C terminates the main thread, but because your threads aren’t in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
s = SecondThread()
s.daemon = True

But then there’s another problem – once the main thread has started your threads, there’s nothing else for it to do. So it exits, and the threads are destroyed instantly. So let’s keep the main thread alive:

import time
while True:

Now it will keep print ‘first’ and ‘second’ until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

This question is answered By – Thomas K

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0