使用 Python 脚本查找 USB 串口

Find USB serial port with Python script

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

直到现在我已经在 batch/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

如果 Python 说字符串不一样,我敢说它们很可能不一样。

您可以比较:

if  "USB Serial Port" in devs[i]:

那么您应该能够找到的不是一个完整的字母匹配项,而是一个包含 USB 端口的匹配项。

不需要使用 numpy,devs 已经是一个列表,因此是可迭代的。

这是@MacrosG 的跟进回答
我尝试了一个带有 Device

属性的最小示例
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)

如果你想用正则表达式来做到这一点:

def main():

    from infi.devicemanager import DeviceManager
    import re

    device_manager = DeviceManager()
    device_manager.root.rescan()

    pattern = r"USB Serial Port \(COM(\d)\)"

    for device in device_manager.all_devices:
        try:
            match = re.fullmatch(pattern, device.friendly_name)
        except KeyError:
            continue
        if match is None:
            continue
        com_number = match.group(1)
        print(f"Found device \"{device.friendly_name}\" -> com_number: {com_number}")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

Found device "USB Serial Port (COM3)" -> com_number: 3

非常感谢大家,尤其是 bigdataolddriver,因为我采用了他的解决方案

最后一件事!

for d in devs:
    if  "USB Serial Port" in d.description :
        str = d.__str__()
        COMport = str.split('(', 1)[1].split(')')[0]
        i=1
        break
    else:
        i=0

if i == 1:
    print ("I found it!")
    print(d.description, "found on : ", COMport)
    subprocess.Popen(r'"C:\Tools\putty.exe" -serial ', COMport)
elif i ==0:
    print ("USB Serial Not found \nPlease check physical connection.")
else:
    print("Error")

知道如何将 COM 端口作为参数传递给 putty.exe 吗?

=====更新=====

if i == 1:
    print ("I found it!")
    print(d.description, "found on : ", COMport)
    command = '"C:\MyTools\putty.exe" -serial ' + COMport
    #print (command)
    subprocess.Popen(command)

谢谢大家!