Python 串行导入错误

Error on Python serial import

当我尝试导入序列号时出现以下错误:

Traceback (most recent call last):
  File "C:\Documents and Settings\eduardo.pereira\workspace\thgspeak\tst.py", line 7, in <module>
    import serial
  File "C:\Python27\lib\site-packages\serial\__init__.py", line 27, in <module>
    from serial.serialwin32 import Serial
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 15, in <module>
    from serial import win32
  File "C:\Python27\lib\site-packages\serial\win32.py", line 182, in <module>
    CancelIoEx = _stdcall_libraries['kernel32'].CancelIoEx
  File "C:\Python27\lib\ctypes\__init__.py", line 375, in __getattr__
    func = self.__getitem__(name)
  File "C:\Python27\lib\ctypes\__init__.py", line 380, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'CancelIoEx' not found

我已经安装了最新版本的 pySerial,Python 2.7 在 WinXP 笔记本电脑上运行。到处都试过了,没有发现类似的问题。有什么解决办法吗? 提前致谢...

您使用的 pySerial 版本正在尝试调用仅在 Windows Vista 中可用的 function,而您使用的是 运行 Windows XP .

可能值得尝试使用旧版本的 pySerial。

有问题的代码是 added to pySerial on 3 May 2016,因此之前的版本可能是一个好的开始。

旧版本似乎不可用。但是,这对我有用(假设 nanpy 版本 3.1.1):

  1. 打开文件\lib\site-packages\serial\serialwin32.py
  2. 删除第 436-455 行接近文件底部的方法 _cancel_overlapped_io()cancel_read()cancel_write()
  3. 更改方法 _close() 如下:

(Python)

def _close(self):
    """internal close port helper"""
    if self._port_handle is not None:
        # Restore original timeout values:
        win32.SetCommTimeouts(self._port_handle, self._orgTimeouts)
        # Close COM-Port:
        if self._overlapped_read is not None:
            win32.CloseHandle(self._overlapped_read.hEvent)
            self._overlapped_read = None
        if self._overlapped_write is not None:
            win32.CloseHandle(self._overlapped_write.hEvent)
            self._overlapped_write = None
        win32.CloseHandle(self._port_handle)
        self._port_handle = None

此外,在开始通信时创建一个非默认串行连接,否则您将绑定到某些 linux 设备:

a = ArduinoApi(SerialManager("COM5:"))

for i in range(10):
    a.pinMode(13, a.OUTPUT)
    a.digitalWrite(13, a.HIGH)
    # etc.

并在 serial\win32.py 评论中

#CancelIoEx = _stdcall_libraries['kernel32'].CancelIoEx
#CancelIoEx.restype = BOOL
#CancelIoEx.argtypes = [HANDLE, LPOVERLAPPED]