我一直在寻找在用户中断后停止线程,但由于某种原因它不能为我工作。谁能帮忙。问题是程序只是忽略了键盘中断错误,键盘中断后它没有关闭。
#!/usr/bin/env python
#
#
from time import sleep
from Queue import Queue
from threading import Thread,Event,Lock
def Count():
global Exit
for i in range(5):
try:
if not Exit.is_set():
with l:
print i;sleep(2)
except KeyboardInterrupt:
Exit.set()
if __name__ == '__main__':
l = Lock()
q = Queue()
Exit = Event()
for i in range(2):
Bot = Thread(target=(Count)).start()
q.put(Bot)
#q.join()
#OutPut
0
1
^C2
3
4
0
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
答案 0 :(得分:0)
您要完成的目标尚不完全清楚。所以我重新组织了你的代码。
from time import sleep
from threading import Thread, Event
def count():
global exit_event
for i in range(5):
try:
if not exit_event.is_set():
print i
sleep(2)
except KeyboardInterrupt:
print "Interrupt in thread"
exit_event.set()
exit_event = Event()
bot = Thread(target=count)
bot.start()
while not exit_event.is_set():
try:
sleep(0.1)
except KeyboardInterrupt:
print "Interrupt in main loop"
exit_event.set()
bot.join()