Python 2.7:子线程没有捕获KeyboardInterrupt

时间:2013-10-06 12:26:13

标签: python multithreading exception python-2.7 keyboardinterrupt

import sys 
import time
import threading

class exThread(threading.Thread):
    def __init__(self, threadId):
        threading.Thread.__init__(self)
        self.threadId = threadId

    def run(self):
        try:
            while 1:
                pass
        except KeyboardInterrupt:
            print "Ctrl-C caught by thread"
        finally:
            print "Thread's finally clause being executed" 
            sys.exit() # Same as thread.exit()

cond = True
def func():
    pass

try:
    th = exThread(1)
    th.start()
    while True:
        if cond:
            func()
except KeyboardInterrupt:
    print "Ctrl-C caught by main thread"
    sys.exit(0)
finally:
    print "Executing the finally clause from main thread"

在执行上面的代码时,当我按下Ctrl-C时,主线程在从finally子句打印后退出。现在,由于子线程是非守护进程,它仍然在try:除KeyboardInterrupt块之外运行。但是,这个子线程似乎没有响应Ctrl-C,即使它应该捕获KeyboardInterrupt异常。为什么呢?

1 个答案:

答案 0 :(得分:1)

据我所知,KeyboardInterrup仅在主线程中引发。为了能够阻止其他线程,让他们不时检查一个事件,然后自愿退出。

另一种选择是将子线程标记为daemon=True,以便在主线程终止时自动终止:

th.daemon = True

补充阅读: