我跑我这简单的代码:线程忽略KeyboardInterrupt异常
import threading, time
class reqthread (threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
def run (self):
for i in range(0,10):
time.sleep(1)
print '.'
try:
thread=reqthread()
thread.start()
except (KeyboardInterrupt, SystemExit):
print '\n! Received keyboard interrupt, quitting threads.\n'
但是当我运行它,它打印
$ python prova.py
`
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
`
其实蟒蛇线程无视我按Ctrl +Ç键盘中断并不打印Received Keyboard Interrupt
。为什么?这段代码有什么问题?
我相信'join'上的超时,即'while thread.isAlive:thread.join(5)'也可以使主线程响应异常。 – 2012-09-11 19:51:03
'thread.daemon = True'实际上并不推荐,因为它不允许线程清理掉任何留下的资源...... – 2013-09-29 14:47:59