如何自动获取端口号。 python 串行通信中的硬件?

How to automatically get port no. of a hardware in python serial communcation?

我正在开发一个 python GUI 用于与一些人进行串行通信 hardware.I 我正在使用 USB-RS232 转换器 that.I 不希望用户寻找硬件的 com 端口在设备管理器中,然后在 communication.How 的 GUI 中 select 端口号 我的 python 代码可以自动获取端口号吗?对于那个特定的 USB 端口?我每次都可以将我的硬件连接到那个特定的端口,如果我 运行 其他 PC.You 中的 GUI 可以为此提出任何其他解决方案,将会发生什么。

提前致谢!!!

pyserial 可以列出带有 USB VID:PID 编号的端口。

from serial.tools import list_ports
list_ports.comports()

这个函数returns一个元组,第3项是一个字符串,可能包含USB VID:PID号码。你可以从那里解析它。或者更好的是,您可以使用 list_ports 模块也提供的 grep 函数:

list_ports.grep("6157:9988")

这个 returns 一个可以迭代的生成器对象。如果不太可能有 2 个设备连接到相同的 VID:PID(我不会假设,但出于测试目的没关系)你可以这样做:

my_port_name = list(list_ports.grep("0483:5740"))[0][0]

list_ports 的文档。

注意:我仅在 linux 上对此进行了测试。 pyserial 文档警告说在某些系统上可能不会列出硬件 ID。

我假设您是专门寻找在设备管理器中被描述为 USB 到 RS232 的 COM 端口,而不是想列出所有可用的 COM 端口?

另外,你没有提到你正在开发什么 OS,或者你正在使用的 Python 版本,但这对我来说在 Windows 系统上使用 Python 3.4:

import serial.tools.list_ports

def serial_ports():

    # produce a list of all serial ports. The list contains a tuple with the port number, 
    # description and hardware address
    #
    ports = list(serial.tools.list_ports.comports())  

    # return the port if 'USB' is in the description 
    for port_no, description, address in ports:
        if 'USB' in description:
            return port_no