Python 2.7:子线程无法捕获KeyboardInterrupt [英] Python 2.7: Child thread not catching 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时, ain线程从其finally子句打印后退出。现在,由于子线程是一个非守护程序,因此它仍在try中运行:KeyboardInterrupt块除外。但是,此子线程似乎不响应Ctrl-C,即使它应该捕获KeyboardInterrupt异常也是如此。为什么?
On executing above code, when I press Ctrl-C, the main thread exits after printing from its finally clause. Now, since the child thread is a non-daemon, it is still running in the try: except KeyboardInterrupt block. However, this child thread doesn't seem to respond to Ctrl-C, even though it is supposed to catch KeyboardInterrupt exception. Why?
推荐答案
据我所知,仅提出了 KeyboardInterrup
在主线程中。为了能够停止其他线程,使它们不时检查事件,然后自动退出。
As far as I know, KeyboardInterrup
is only raised in the main thread. To be able to stop the other threads, make them check for an event from time to time, and then exit voluntarily.
另一种选择是将子线程标记为 daemon = True
,这样它将在主线程终止时自动终止:
Another option is to mark the child thread as daemon=True
so that it will auto-terminate when the main thread terminates:
th.daemon = True
其他阅读:
- 守护程序线程如何工作守护程序线程说明
- 但是,守护程序线程也可能有害: http:// joeshaw .org / 2009/02/24/605 /
- How daemon threads work Daemon Threads Explanation
- But also, daemon threads can be harmful: http://joeshaw.org/2009/02/24/605/
这篇关于Python 2.7:子线程无法捕获KeyboardInterrupt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!