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异常。为什么?Python 2.7:子线程不捕捉KeyboardInterrupt
在Python中,类名应该是'CapitalizedCamelCase'。 –