Python pyserial 错误 - 无法打开端口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20879939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:27:07  来源:igfitidea点击:

pyserial error - cannot open port

pythonusbpyserial

提问by user3153016

I have seen simple code in stackoverflow using pyserial in USB ports with Python 3.3 but I can't get this to work on my new installation of pyserial 2.7 [in Windows 7, 64 bit, with 3 USB ports]. Installation of pyserial went smoothly, I can import without error and methods are recognized in the Pyscripter IDE which boosts confidence in a good installation, however:

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

The code stripped down to its error producing essentials is:

精简到其错误产生要素的代码是:

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

if __name__ == '__main__':
   main

From this I receive a dialog box with the error "SerialException: could not open port 'COM2': FileNotFoundError(2,'The system cannot find the file specified.',None,2)"

从此我收到一个错误对话框“SerialException: could not open port 'COM2': FileNotFoundError(2,'The system cannot find the file specified.',None,2)”

The Traceback states:

回溯指出:

*** 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)

And the code segment in the imported module which raises the SerialException is:

导入模块中引发 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()))

I do have an active device connected to COM2 as identified in the Windows device manager. I also have tried scanning all the ports, but the code stops on the first use of serial.Serial

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

This appears that something may be going on with win32?

这似乎是 win32 上可能发生的事情?

I am a newbie for interfacing Python with hardware.

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

回答by David Grayson

I would try the following:

我会尝试以下方法:

  • Unplug and replug the device.
  • Reboot.
  • Run WinObjand look in the GLOBAL??folder; you should see COM2 there as a symbolic link to something more driver-specific.
  • What type of device do you have connected to COM2? If it uses usbser.sys, you might have better luck substituting \\.\USBSER000for COM2in your code, but remember to escape those backslashes properly.
  • On some machines there are strange problems with low COM port numbers that I can't explain. Try reassigning the device to COM6 in the Device Manager.
  • 拔下并重新插入设备。
  • 重启。
  • 运行WinObj并查看GLOBAL??文件夹;您应该将 COM2 视为指向更特定于驱动程序的内容的符号链接。
  • 您连接到 COM2 的是什么类型的设备?如果使用usbser.sys,你可能有更好的运气代\\.\USBSER000用于COM2在你的代码,但记得要正确逃生的反斜线。
  • 在某些机器上,COM 端口号低会出现一些我无法解释的奇怪问题。尝试在设备管理器中将设备重新分配给 COM6。

回答by Peter Gibson

It looks like the pyserial download pageonly contains links for 32 bit python? This unofficial pageseems to have links for 64 bit installations, however be cautious installing from unknown sources.

看起来pyserial下载页面只包含32位python的链接?这个非官方页面似乎有 64 位安装的链接,但是从未知来源安装时要小心。

This answer also suggests installing it using pip: https://stackoverflow.com/a/8491164/66349

这个答案还建议使用pip以下方法安装它:https: //stackoverflow.com/a/8491164/66349