在多处理过程中无法使用try

时间:2018-02-25 14:04:43

标签: python multiprocessing try-catch

我正在写一个eventEngine。我发现如果我注释掉了try,除了在函数“run”中,它可以正常工作,虽然它会在Queue为空时引发Empty错误。但是,如果我不评论尝试...除了,它将无法正常工作!这让我感到困惑。当Queue对象为空时,它将引发Empty错误,所以我应该尝试捕获它,但try语句似乎使run函数完全崩溃:在运行中不输出任何内容。

python ver.3.6.4 windows 7

from multiprocessing import Process,Queue

from time import sleep

from collections import defaultdict

import time

from eventType import *

class EventEngine(object):

    def __init__(self):
        self.queue = Queue()
        self.active = False

        self.handlers = defaultdict(list) 

        self.dealprocess=Process(target=self.run)

        self.timerActive = False          
        self.timerSleep = 1            
        self.timer = Process(target=self.runTimer) 
    #----------------------------------------------------------------------
    def run(self):
        print('----- it's run func -----')
        while self.active:
            try:  # comment out it
                event = self.queue.get(True,timeout=1) 
                if event.type_ in self.handlers:
                    [handler(event) for handler in self.handlers[event.type_]] 
            except :  # comment out it
                print('++++++++++++++')  # comment out it
                continue  # comment out it

    def runTimer(self):
        print('******************')
        event = Event(type_=EVENT_TIMER)
        self.queue.put(event)    
    #----------------------------------------------------------------------
    def start(self, timer=True):
        self.active = True
        self.dealprocess.start()
        if timer:
            self.timerActive = True
            self.timer.start()
    #----------------------------------------------------------------------
    def put(self, event):
        self.queue.put(event)

########################################################################
class Event:

    def __init__(self, type_=None):
        """Constructor"""
        self.type_ = type_  
        self.dict_ = {}     

def simpletest(event):

    print('------successfully handled the event----------')

#----------------------------------------------------------------------
def test():

    import sys

    from PyQt5.QtCore import QCoreApplication

    app = QCoreApplication(sys.argv)

    ee = EventEngine()

    ee.register(EVENT_TIMER, simpletest)

    ee.start()

    app.exec_()

if __name__ == '__main__':

    test()

输出(注释掉试试......除外):

-----它运行func -----

------成功处理了事件----------

输出(不要注释掉试试......除外)

0 个答案:

没有答案