Python pyserial错误-无法打开端口
我在stackoverflow中看到了在Python 3.3的USB端口中使用pyserial的简单代码,但在我新安装的pyserial 2.7(在Windows 7中,64位,具有3个USB端口)上无法实现这一点。pyserial的安装进展顺利,我可以毫无错误地导入,并且Pyscripter IDE中可以识别方法,这增强了对良好安装的信心,但是: 简化为错误生成要素的代码是:Python pyserial错误-无法打开端口,python,usb,pyserial,Python,Usb,Pyserial,我在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'
import serial
def main():
ser = serial.Serial(port='COM2')
ser.close()
if __name__ == '__main__':
main
由此,我收到一个对话框,错误为“SerialException:无法打开端口'COM2':FileNotFoundError(2,'系统找不到指定的文件',无,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)
我确实有一个连接到COM2的活动设备,如Windows设备管理器中所示。我也尝试过扫描所有端口,但是第一次使用serial.serial时代码就停止了
看来win32可能有问题
我是一个将Python与硬件接口的新手 我会尝试以下方法:
- 拔下并重新插入设备
- 重新启动
- 运行并查看
文件夹;您应该将COM2视为指向更特定于驱动程序的符号链接GLOBAL???
- 您连接到COM2的设备类型是什么?如果它使用usbser.sys,那么在代码中用
替换\\.\USBSER000
可能会更好,但请记住正确地避开这些反斜杠COM2
- 在一些机器上,我无法解释COM端口号低的奇怪问题。尝试在设备管理器中将设备重新分配给COM6
此答案还建议使用
pip
安装它:我不熟悉Windows的权限,但您是否尝试以管理员身份运行代码?我发现使用\.\COMx
格式对于端口COM8
来说是必要的。请在每个系统的命令提示下执行“pip冻结”。如果您有不同的pyserial主要版本,这可能是根本原因。com端口引用从2.x更改为3.x(以前是整数,现在是字符串),即,如果新安装有pyserial 2.x,则需要调用“ser=serial.serial(port=2)”pyserial是否与gpsfeed+一起工作?gpsfeed+在COM14800上生成数据。但是我得到“serialutil.SerialException:[Errno 2]无法打开端口COM14800:[Errno 2]没有这样的文件或目录:'com14800'”
# 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()))