KeyboardInterrupt

Lie Ryan lie.1296 at gmail.com
Fri Dec 11 03:33:35 CET 2009


On 12/11/2009 10:43 AM, mattia wrote:
> Ok, so is there any way to stop all the threads if the keyboard interrupt
> is received?

You can't stop a thread from outside. The thread has to end itself (by 
ending the function). Usually, in the thread, you will check the value 
of a variable. If it's false, then it's time to stop and head to the end 
of the function.

# global, or better use a Quit sentinel in a Queue
import time, sys
from threading import Thread
running = True

def do_work():
     while True:
         time.sleep(1)
         print(".", end="")
         sys.stdout.flush()
         if running == False:
             break
     print('thread ended')

def go():
     global running
     threads = [Thread(target=do_work, args=()) for _ in range(2)]
     for t in threads:
         t.start()
     try:
         while running:
             time.sleep(1)
             running = any(t.is_alive() for t in threads)
     except KeyboardInterrupt:
         running = False




More information about the Python-list mailing list