在Python中创建串行对象时遇到问题

在Python中创建串行对象时遇到问题,python,serial-port,Python,Serial Port,我正在编写一个程序,该程序应该使用串行对象与Arduino装置进行通信。在类的init-方法中,可以找到这段代码: try: self.rotor = serial.Serial(port = "COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1) except serial.SerialException, e: print "Error when connecting to col

我正在编写一个程序,该程序应该使用串行对象与Arduino装置进行通信。在类的init-方法中,可以找到这段代码:

    try:
        self.rotor  = serial.Serial(port = "COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1)
    except serial.SerialException, e:
        print "Error when connecting to collimator: ", e
当我运行它时,会收到以下错误消息:

SerialException: could not open port 'COM1': WindowsError(2, 'The system cannot find the file specified.')
我让电脑打开COM22,它回答说无法打开COM1。什么 那是怎么回事?Arduino装置插入COM22


我有另一个程序,我还没有自己编写,但它使用相同的类库。这个程序有效,但我不明白怎么做。是否有一些串行对象的初始化我没有完成?

来自PySerial SVN trunk()中
Win32Serial
对象的源代码:

因此,将代码更改为:

    try:
        self.rotor  = serial.Serial(port = r"\\.\COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1)
    except serial.SerialException, e:
        print "Error when connecting to collimator: ", e

应该可以正常工作。

我后来发现错误源于错误定义的模块路径 用类定义。该路径指向的是旧版本的
相同的文件。

错误可能发生在其他地方。如果错误发生在代码中,您的try-catch仍将捕获该错误。
    try:
        self.rotor  = serial.Serial(port = r"\\.\COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1)
    except serial.SerialException, e:
        print "Error when connecting to collimator: ", e