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: except KeyboardInterrupt 块中运行。然而,这个子线程似乎没有响应 Ctrl-C,即使它应该捕获 KeyboardInterrupt 异常。为什么?