Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python串行通信中自动获取硬件的端口号?_Python_Serial Port_Pyserial - Fatal编程技术网

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

如何在python串行通信中自动获取硬件的端口号?,python,serial-port,pyserial,Python,Serial Port,Pyserial,我正在开发一个python GUI,用于与某些硬件进行串行通信。我正在使用USB-RS232转换器进行串行通信。我不希望用户在设备管理器中查找硬件的com端口,然后在GUI中选择端口号进行通信。我的python代码如何自动获取该特定USB端口的端口号?我可以将硬件连接到如果我在其他电脑上运行GUI,那么每次都会发生这种情况。你可以为此建议任何其他解决方案 提前感谢 pyserial可以列出带有USB VID:PID编号的端口 from serial.tools import list_ports

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


提前感谢

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

from serial.tools import list_ports
list_ports.comports()
此函数返回一个元组,第三项是可能包含USB VID:PID编号的字符串。你可以从那里解析它。或者更好,您可以使用
list\u ports
模块提供的
grep
功能:

list_ports.grep("6157:9988")
这个函数返回一个生成器对象,您可以对其进行迭代。如果不太可能有两个设备连接到同一个VID:PID(我不会假设,但出于测试目的,这是可以的),您可以这样做:

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


注意:我只在linux上测试过这个。pyserial文档警告说,某些系统上可能未列出硬件ID。

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

from serial.tools import list_ports
list_ports.comports()
此函数返回一个元组,第三项是可能包含USB VID:PID编号的字符串。你可以从那里解析它。或者更好,您可以使用
list\u ports
模块提供的
grep
功能:

list_ports.grep("6157:9988")
这个函数返回一个生成器对象,您可以对其进行迭代。如果不太可能有两个设备连接到同一个VID:PID(我不会假设,但出于测试目的,这是可以的),您可以这样做:

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


注意:我只在linux上测试过这个。pyserial文档警告说,在某些系统上,可能没有列出硬件ID。

我假设您正在寻找一个COM端口,该端口在设备管理器中被描述为USB到RS232,而不是列出所有可用的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

我假设您正在寻找一个COM端口,该端口在设备管理器中被描述为USB到RS232,而不是列出所有可用的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