PySerial 在读取期间抛出 'NoneType' 异常()

PySerial Throwing 'NoneType' Exception During read()

我正在使用 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)

异常告诉 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_readmcuPort.open(...

之后是否 不是 None

除此之外,请检查您是否有最新的 pySerial module

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

问题是由于我关闭端口的方式的异步性质。在我的退出例程中,我在清除 'testRunning' 之前关闭了端口。然后循环将在完成之前经历一次不稳定的迭代。在关闭端口之前清除 'testRunning' 锁可以防止这种不稳定的迭代。

之前

def quitTest(self):

    global testRunning
    global mcuPort

    #Close all open ports
    if(mcuPort.is_open):
        mcuPort.close()


    testRunning = False

之后

def quitTest(self):

    global testRunning
    global mcuPort


    testRunning = False

    #Close all open ports
    if(mcuPort.is_open):
        mcuPort.close()