1
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

+0

在Python中,类名应该是'CapitalizedCamelCase'。 –

回答

1

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

另一种选择是,以纪念子线程作为daemon=True,这样它会自动终止,当主线程终止:

th.daemon = True 

补充阅读:

+0

您可以引用您创建的第一个文档的文档吗?因为至少对于线程模块(http://docs.python.org/2/library/thread.html),我引用了“线程与中断奇怪地交互:KeyboardInterrupt异常将被任意线程接收(当信号模块可用,中断总是进入主线程。)“ – gjain

+0

守护线程不是一个选项,因为我需要子线程优雅地终止 – gjain

+0

因此,使用退出事件信号方法;关于该文档:你自己说过:*“当信号模块可用时,中断总是进入主线程。”* ...如果'signal'可用,主线程将获得它;但我不知道是什么决定了它的可用性。 –