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

14,078

Solution 1

pyserial can list the ports with their USB VID:PID numbers.

from serial.tools import list_ports
list_ports.comports()

This function returns a tuple, 3rd item is a string that may contain the USB VID:PID number. You can parse it from there. Or better, you can use the grep function also provided by list_ports module:

list_ports.grep("6157:9988")

This one returns a generator object which you can iterate over. If it's unlikely that there are 2 devices connected with the same VID:PID (I wouldn't assume that, but for testing purposes its okay) you can just do this:

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

Documentation for list_ports.

Note: I've tested this on linux only. pyserial documentation warns that on some systems hardware ids may not be listed.

Solution 2

I assume that you are specifically looking for a COM port that is described as being a USB to RS232 in the device manager, rather than wanting to list all available COM ports?

Also, you have not mentioned what OS you are developing on, or the version of Python you are using, but this works for me on a Windows system using 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
Share:
14,078
curiousAsKid
Author by

curiousAsKid

Updated on July 14, 2022

Comments

  • curiousAsKid
    curiousAsKid almost 2 years

    I am working on a python GUI for serial communication with some hardware.I am using USB-RS232 converter for that.I do'nt want user to look for com port of hardware in device manager and then select port no in GUI for communication.How can my python code automatically get the port no. for that particular USB port?I can connect my hardware to that particular everytime and what will happen if i run the GUI in some other PC.You can suggest any other solution for this.

    Thanks in advance!!!