如何解决在python中,如何通过使用另一个监听按键的线程来停止一个线程?
在这里,我为两个线程使用两个类。以下Capture类完成了主要工作。
class Capture(Thread):
def __init__(self,path=PATH):
Thread.__init__(self)
self.daemon = False
self.cap = cv2.VideoCapture(path)
self.grabbed,self.frame = self.cap.read()
self.stop = False
self.start()
def __del__(self):
self.cap.release()
def __capture_frame(self):
# while not self.grabbed:
# self.grabbed,self.frame = self.cap.read()
print('running')
cv2.waitKey(10)
# cv2.imshow('frame',self.frame)
def get_frame(self):
self.__capture_frame()
self.__wait=True
def run(self):
while True & (not self.stop):
self.get_frame()
def stop_thread(self):
self.stop = True
然后,我还有另一个班级正在听按键或例外情况。我正在使用try语句,以便可以使用“ ctrl + c”键盘中断来停止它。
class KeyStroke(Thread):
def __init__(self,listen_to):
Thread.__init__(self)
self.daemon = False
self.listen_to = listen_to
self.start()
def run(self):
try:
while True:
if cv2.waitKey(10) & 0xFF == ord('q'):
self.listen_to.stop_thread()
self.listen_to.join()
break
print('listening to... ',self.listen_to)
except:
self.listen_to.stop_thread()
self.listen_to.join()
pass
然后我像这样在主线程中启动工作线程。
KeyStroke(Capture())
这两个线程都开始运行,但是它们都没有因我的键盘中断而停止。同样,它也没有响应“ q”新闻。我正在使用Spyder。
我在做什么错了?
但是,当我在主线程中运行以下代码时,它会因键盘中断异常而停止。
cap = Capture()
try:
while True:
if cv2.waitKey(10) & 0xFF == ord('q'):
cap.stop_thread()
cap.join()
except:
cap.stop_thread()
cap.join()
pass
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。