2017-05-11 61 views
0

我正在使用PySerial從串行端口讀取傳入的字節到緩衝區。每次我打電話給我的閱讀功能這個異常被拋出。PySerial拋出'NoneType'異常在讀取期間()

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

例外告訴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是設置NonemcuPort.open(...

在這旁邊檢查,如果您有最新的pySerial module

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

1

問題是由於我關閉端口的異步性質。在我的退出例程中,我在清除「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()