Cannot Kill Python Script With Ctrl-C


Answer :

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 f.start() s = SecondThread() s.daemon = True s.start() 

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:     time.sleep(1) 

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.


KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python


I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.

import threading import time  class MyThread (threading.Thread):     die = False     def __init__(self, name):         threading.Thread.__init__(self)         self.name = name      def run (self):         while not self.die:             time.sleep(1)             print (self.name)      def join(self):         self.die = True         super().join()  if __name__ == '__main__':     f = MyThread('first')     f.start()     s = MyThread('second')     s.start()     try:         while True:             time.sleep(2)     except KeyboardInterrupt:         f.join()         s.join() 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?