I been looking at stopping a thread after user interruption, but for some reason it's not working for me. Can anyone help. The issue is the program just ignores the keyboard interruption error, it's not shutting down after the keyboard interruption.
#!/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
It is not entirely clear what you are trying to accomplish. So i restructured your code.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.