我跑我這簡單的代碼:線程忽略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