尝试捕获不在子线程中工作

时间:2017-05-22 21:40:54

标签: python multithreading

我有一个运行while-true循环的线程:

from threading import Thread, Event

class MyThread(Thread):
    def __init__(self, thread_id, name, counter, thread_func):
        Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name
        self.counter = counter
        self.thread_func = thread_func
        self._stop_event = Event()

    def run(self):
        try:
            while True:
                self.thread_func()
        except KeyboardInterrupt:
            print 'keyboard interrupt'
            self.stop()

    def stop(self):
        """
        stops the thread
        """
        self._stop_event.is_set()

目标是捕获KeyboardInterrupt事件并停止线程。但是,我无法通过中断执行except块。但是,当我在主线程上放置此try / catch时,它可以正常工作。我做错了什么?

1 个答案:

答案 0 :(得分:1)

子线程未收到键盘中断。您可以在主线程中捕获异常并执行回调,例如,杀死子线程。 这是一个示例代码示例:

import threading
if __main__ == "__name__":
    t1 = threading.Thread()
    t2 = threading.Thread()
    try:
       t1.start()
       t2.start()
    except KeyboardInterrupt as e:
       t1.join()
       t2.join()