How can I fix “[Error 6] The handle is invalid.” with PySerial

前端 未结 5 2019
一个人的身影
一个人的身影 2020-12-11 04:25

I\'m trying to connect to my phone from my Windows 7 PC using PySerial with the following code:

import wmi
import serial

c = wmi.WMI()
modem = c.query(\"SEL         


        
5条回答
  •  暖寄归人
    2020-12-11 05:07

    I'm on windows 7 64 bit, with python 2.6, and it's giving me the same error.

    ser = serial.Serial(3,115200,timeout=1)
    ser.read()
    #or ser.write("whatever")
    
    Traceback (most recent call last):
      File "", line 1, in 
        ser.read(1)
      File "build\bdist.win-amd64\egg\serial\serialwin32.py", line 236, in read
        raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
    SerialException: ReadFile failed ([Error 6] The handle is invalid.)
    

    When using a similar program using a c library, the same port responds correctly. What happens here? Sounds like a bug in either pyserial or ctypes. Are you using 64 bit too?

    the source code for writing in pyserial looks very simple

    def write(self, data):
            """Output the given string over the serial port."""
            if not self.hComPort: raise portNotOpenError
            #~ if not isinstance(data, (bytes, bytearray)):
                #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
            # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
            data = bytes(data)
            if data:
                #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
                n = win32.DWORD()
                err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite)
                if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
                    raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
    

    perhaps a problem with 64 bit ctypes?


    Update: Definitly a 64 bit problem atleast for me. I just installed an x86 version of python (3.1 this time), and it now works fine. Apperantly 64 bit ctypes can only import 64 bits libraries. Sounds very strange not being able to reach operating system libraries though.

提交回复
热议问题