Python while循环在“try”之前不会执行

2024-04-20 00:39:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一个非常简单的python while循环:

def run(self):
    while True:
        self.__main_thread.ask('wake',{})
        time.sleep(0.25)

在我将代码更改为以下内容之前,不会执行“ask”函数:

def run(self):
    while True:
        try:
            self.__main_thread.ask('wake',{})
        except:
            print(sys.exc_info())
        time.sleep(0.25)

这是一个线程类,我想做一些与主线程并行的工作。你知道吗

以下是“询问”和“唤醒”功能:

    def ask(self, action, arguments):
        if hasattr(self, action) and callable(getattr(self, action)):
            try:
                return getattr(self, action)(arguments)
            except:
                self.__exception_queue.put(sys.exc_inf())
        else:
            error = {'errCode':'ERR_00',"logMsg": "Invalid action: requested action '%s' is not implemented." % action}
            print (error)
            return error 


def wake(self):
    pic=None
    try:
        frame = self.webcam.read()[1]
        frame = cv2.resize(frame, (300, 300,interpolation=cv2.INTER_CUBIC)
        pic = cv2.imencode('.png',frame)[1]
    except:
        if self.debug:
            print ('no picture available')
        raise
     else:
        self._photo_b64 = base64.encodestring(pic)

基本上,我试着用一个线程周期性地从我的网络摄像头中读取。 如果我将“try”和“except”添加到“run”函数中,网络摄像头图像将按预期更新,否则,不会从网络摄像头读取图像,也不会引发异常。你知道吗


Tags: runself网络defactionerrorcv2frame