【问题标题】:How to automatically get port no. of a hardware in python serial communcation? [duplicate]如何自动获取端口号python串行通信中的硬件? [复制]
【发布时间】:2015-08-14 07:13:18
【问题描述】:

我正在开发用于与某些硬件进行串行通信的 python GUI。我正在使用 USB-RS232 转换器。我不希望用户在设备管理器中查找硬件的 com 端口,然后在 GUI 中选择端口号用于通信。我的python代码如何自动获取端口号。对于那个特定的 USB 端口?我可以每次都将我的硬件连接到那个特定的端口,如果我在其他 PC 上运行 GUI 会发生什么。你可以为此建议任何其他解决方案。

提前致谢!!!

【问题讨论】:

    标签: python serial-port pyserial


    【解决方案1】:

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

    另外,你没有提到你正在开发什么操作系统,或者你正在使用的 Python 版本,但这适用于我在使用 Python 3.4 的 Windows 系统上:

    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
    

    【讨论】:

      【解决方案2】:

      pyserial 可以列出端口及其 USB VID:PID 编号。

      from serial.tools import list_ports
      list_ports.comports()
      

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

      list_ports.grep("6157:9988")
      

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

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

      list_ports 的文档。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-09
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-23
        • 2014-01-11
        相关资源
        最近更新 更多