线程忽略KeyboardInterrupt异常 [英] threading ignores KeyboardInterrupt exception
问题描述
我正在运行我的简单代码:
导入线程,时间
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'\\\
!接收到键盘中断,退出threads.\\\
'
但是当我运行它时,它打印
$ python prova.py
`
。
。
^ C。
。
。
。
。
。
。
。
从< module'threading'from'/usr/lib/python2.6/threading.pyc'>中的异常KeyboardInterrupt;忽略
`
其实python线程忽略我的 Ctrl + C 键盘中断,不打印接收到的键盘中断
。为什么?这个代码有什么问题?
尝试
try:
thread = reqthread()
thread.daemon = True
thread.start()
while True:time.sleep(100)
除了(KeyboardInterrupt,SystemExit):
打印'\\\
!收到键盘中断,退出线程。\ $'
没有调用 time.sleep
,主要过程是跳出 try ...除了
块太早,所以$ code KeyboardInterrupt 未被捕获。我的第一个想法是使用 thread.join
,但是似乎阻止主程序(忽略KeyboardInterrupt),直到线程
完成。
thread.daemon = True
导致线程在主进程结束时终止。 p>
I'm running this my simple code:
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'
But when i run it, it prints
$ python prova.py
`
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
`
In fact python thread ignore my Ctrl+C keyboard interrupt and doesn't print Received Keyboard Interrupt
. Why? What is wrong with this code?
Try
try:
thread=reqthread()
thread.daemon=True
thread.start()
while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
print '\n! Received keyboard interrupt, quitting threads.\n'
Without the call to time.sleep
, the main process is jumping out of the try...except
block too early, so the KeyboardInterrupt
is not caught. My first thought was to use thread.join
, but that seems to block the main process (ignoring KeyboardInterrupt) until the thread
is finished.
thread.daemon=True
causes the thread to terminate when the main process ends.
这篇关于线程忽略KeyboardInterrupt异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!