pyserial错误-无法打开p

2024-09-25 10:19:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在stackoverflow中看到了在Python 3.3的USB端口中使用pyserial的简单代码,但是我无法在新安装的pyserial 2.7上运行这个程序[在Windows 7中,64位,有3个USB端口]。pyserial的安装进展顺利,我可以毫无错误地导入,Pyscripter IDE中可以识别方法,这增强了对良好安装的信心,但是:

代码分解为产生错误的要素是:

import serial
def main():
  ser = serial.Serial(port='COM2')
  ser.close()

if __name__ == '__main__':
   main

从中我收到一个对话框,错误为“SerialException:无法打开端口“COM2”:FileNotFoundError(2,'系统找不到指定的文件',None,2)”

回溯说明:

*** Remote Interpreter Reinitialized  ***
>>>
Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "C:\Python33\Lib\site-packages\scanport2.py", line 19, in <module>
main()
  File "C:\Python33\Lib\site-packages\scanport2.py", line 15, in main
ser = serial.Serial(port='COM2')
  File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
  File "C:\Python33\Lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
  File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM2': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)

而引发SerialException的导入模块中的代码段是:

    # the "\\.\COMx" format is required for devices other than COM1-COM8
    # not all versions of windows seem to support this properly
    # so that the first few ports are used with the DOS device name
    port = self.portstr
    try:
        if port.upper().startswith('COM') and int(port[3:]) > 8:
            port = '\\\\.\\' + port
    except ValueError:
        # for like COMnotanumber
        pass
    self.hComPort = win32.CreateFile(port,
           win32.GENERIC_READ | win32.GENERIC_WRITE,
           0, # exclusive access
           None, # no security
           win32.OPEN_EXISTING,
           win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
           0)
    if self.hComPort == win32.INVALID_HANDLE_VALUE:
        self.hComPort = None    # 'cause __del__ is called anyway
        raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))

我确实有一个活动设备连接到了Windows设备管理器中标识的COM2。我也试过扫描所有的端口,但是代码在第一次使用serial.serial时就停止了

似乎win32有什么问题?

我是Python与硬件接口的新手。


Tags: inpyselfmainportlibpackagesline
2条回答

我会尝试以下方法:

  • 拔下并重新插入设备。
  • 重新启动。
  • 运行WinObj并查看GLOBAL??文件夹;您应该在那里看到COM2,它是指向更特定于驱动程序的符号链接。
  • 您连接到COM2的设备类型是什么?如果它使用usbser.sys,那么在代码中用\\.\USBSER000替换COM2可能会有更好的运气,但是记住要正确地转义那些反斜杠。
  • 在一些机器上,有一些奇怪的COM端口号低的问题,我无法解释。尝试在设备管理器中将设备重新分配到COM6。

看起来pyserial download page只包含32位python的链接?这个unofficial page似乎有用于64位安装的链接,但是要小心从未知源安装。

这个答案还建议使用piphttps://stackoverflow.com/a/8491164/66349安装它

相关问题 更多 >