需要帮助列出 Python 中 COM 端口上的设备

Need help listing the devices on COMM Ports in Python

我想自动读取连接到计算机的所有设备,以便我可以与所有 Keyspans 和其他设备的 none 通信。我正在使用 Python 和 PySerial 模块。

我最接近的是通过 CMD:

python -m serial.tools.list_ports -v

COM1
    desc: Communications Port (COM1)
    hwid: ACPI\PNP0501
COM3
    desc: Keyspan USB Serial Port (COM3)
    hwid: KEYSPAN\*USA19HMAP[=11=]_00
COM4
    desc: Keyspan USB Serial Port (COM4)
    hwid: KEYSPAN\*USA19HMAP_00
3 ports found


我真的很想使用 python 脚本来获取此信息,例如


print(serial.tools.comports)

但是 returns 就是

[<serial.tools.list_ports_common.ListPortInfo object at 0x00000000044022C8>, 
<serial.tools.list_ports_common.ListPortInfo object at 0x00000000043F8288>, 
<serial.tools.list_ports_common.ListPortInfo object at 0x00000000043F8388>]

我不太确定那是什么意思。如果您有任何建议,我很乐意听取他们的意见!编辑:感谢您的帮助!

您的结果显示 serial.tools.comports 是一个列表,因此您可以使用 for 循环对其进行格式化,或者 运行 一些函数分别处理每个元素。

for item in serial.tools.comports:
    print( item )

使用dir(item)您可以看到该对象中可用的所有方法和属性。

使用 help(item) 你应该看到源代码中的文档。

如果你知道方法,那么你就可以使用它们

for item in serial.tools.comports:
    print("Device:", item.device)
    print("Description:", item.desctiption)

编辑: 根据 ListPortInfo 的文档,您应该

for item in serial.tools.comports:
    print( item.name )
    print( item.description )
    print( item.hwid )
    print( item.vid )
    print( item.pid )
    print( item.serial_number )
    print( item.location )
    print( item.manufacturer )
    print( item.product )
    print( item.interface )