PySerial投掷' NoneType' read()期间的异常

时间:2017-05-11 15:03:30

标签: python multithreading pyserial

我正在使用PySerial将串行端口的传入字节读入缓冲区。每次我调用我的读取函数时,都会抛出此异常。

Exception in thread Thread-2:
Traceback (most recent call last):  
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner  
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run  
    self.__target(*self.__args, **self.__kwargs)
  File "gatewayTester.py", line 480, in mcuRead  
    byteIn = mcuPort.read()
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 269, in read   
    win32.ResetEvent(self._overlapped_read.hEvent)  
AttributeError: 'NoneType' object has no attribute 'hEvent'  

尽管抛出了这个异常,我的应用程序似乎仍能正常运行 但是,我想澄清这个问题的根源。

这是我的串行读取功能。

def mcuRead(self, *args, **kwargs):

    global mcuPort
    global readVal
    global serialWriting
    global testRunning

    print("READING MCU")
    sys.stdout.flush()
    inBuffer = ""

    while testRunning:
        try:
            byteIn = ""
            if not mcuPort.is_open:
                mcuPort.open()

            #Read incoming byte 
            if not serialWriting:
                byteIn = mcuPort.read()
                inBuffer += byteIn
                #Skip newlines to parse incoming commands
                if(byteIn == "\n"):                     
                    inBuffer = ""

                #Check if buffer contains a valid command
                for rxCmd in mcuRxCmds:

                    if inBuffer == rxCmd['Command']:

                        #store incoming command globally
                        readVal = rxCmd['Command']
                        #Clear buffer
                        inBuffer = ""
                        print("MCU IN "+str(readVal))

        except(OSError, serial.SerialException):
            print(OSError)

        sys.stdout.flush()

串行端口全局创建如下。读取函数在单独的线程上并发运行。

mcuPort = serial.Serial(port, 115200, timeout=0)

1 个答案:

答案 0 :(得分:1)

异常告诉mcuPort._overlapped_readNone

win32.ResetEvent(self._overlapped_read.hEvent)
AttributeError: 'NoneType' object has no attribute 'hEvent' 

这是在def open

中设置的
try:
        self._overlapped_read = win32.OVERLAPPED()
        self._overlapped_read.hEvent = win32.CreateEvent(None, 1, 0, None)

mcuPort._overlapped_read之后检查None mcuPort.open(...是否<{1}}

除了此检查,您是否拥有最新的pySerial module

相关:pywin32/bugs/search/?q=OVERLAPPED