首页 > 解决方案 > 用 Python 脚本查找 USB 串口

问题描述

我正在尝试用 python 编写一个脚本,以便在 1 秒内找到插入笔记本电脑的 USB 串行适配器的 COM 号。我需要的是隔离 COMx 端口,以便我可以显示结果并使用该特定端口打开腻子。你能帮我解决这个问题吗?

到目前为止,我已经在批处理/powershell 中编写了一个脚本,并且我正在获取此信息,但我无法分离 COMx 端口的文本,因此我可以使用串行参数调用 putty 程序。我也能够通过 Python 找到端口,但我无法将其与字符串隔离。

import re           # Used for regular expressions (unused)
import os           # To check that the path of the files defined in the config file exist (unused)
import sys          # To leave the script if (unused)
import numpy as np
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
print ('Type of Devs: ',type(devs))
myarray = ([])
myarray =np.array(devs)
print ('Type of thing: ',type(myarray))
match = '<USB Serial Port (COM6)>' (custom match. the ideal would be "USB Serial Port")
i=0
#print (myarray, '\n')
while i != len(devs):
    if match == myarray[i]: 
        print ('Found it!')
        break
    print ('array: ',i," : ", myarray[i])
    i = i+1
print ('array 49: ', myarray[49]) (here I was checking what is the difference of the "element" inside the array)
print ('match   : ', match) (and what is the difference of what I submitted)
print ('end')

我期待 if match == myarray[i] 找到这两个元素,但由于某种原因它没有。它让我知道这两个是不一样的。

感谢您提前提供任何帮助!

=== 更新 === 完整的脚本可以在这里找到 https://github.com/elessargr/k9-serial

标签: pythonwindowsserial-portusb

解决方案


这是@MacrosG 的后续回答
我尝试了一个带有设备属性的最小示例

from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
for d in devs:
    if  "USB" in d.description :
         print(d.description)


推荐阅读