Identifying USB to serial port given USB VID and PID using pyserial

yogesh kumar picture yogesh kumar · Jan 23, 2016 · Viewed 9.9k times · Source

I am new learner in python. I want create a web application for send sms or call using data card. I have been send sms using data card but my issue that if I use multiple data card connect at a time how can check which usb port working fine or not. So I want get usb serial number or usb pid or vid.

import serial.tools.list_ports;
reslt =  serial.tools.list_ports.comports()
print serial.tools.list_ports.ListPortInfo.name

Result :

[('/dev/ttyS31', 'ttyS31', 'n/a'), ('/dev/ttyS30', 'ttyS30', 'n/a'),
 ('/dev/ttyS29', 'ttyS29', 'n/a'), ('/dev/ttyS28', 'ttyS28', 'n/a'),
 ('/dev/ttyS27', 'ttyS27', 'n/a'), ('/dev/ttyS26', 'ttyS26', 'n/a'),
 ('/dev/ttyS25', 'ttyS25', 'n/a'), ('/dev/ttyS24', 'ttyS24', 'n/a'),
 ('/dev/ttyS23', 'ttyS23', 'n/a'), ('/dev/ttyS22', 'ttyS22', 'n/a'),
 ('/dev/ttyS21', 'ttyS21', 'n/a'), ('/dev/ttyS20', 'ttyS20', 'n/a'),
 ('/dev/ttyS19', 'ttyS19', 'n/a'), ('/dev/ttyS18', 'ttyS18', 'n/a'),
 ('/dev/ttyS17', 'ttyS17', 'n/a'), ('/dev/ttyS16', 'ttyS16', 'n/a'),
 ('/dev/ttyS15', 'ttyS15', 'n/a'), ('/dev/ttyS14', 'ttyS14', 'n/a'),
 ('/dev/ttyS13', 'ttyS13', 'n/a'), ('/dev/ttyS12', 'ttyS12', 'n/a'),
 ('/dev/ttyS11', 'ttyS11', 'n/a'), ('/dev/ttyS10', 'ttyS10', 'n/a'),
 ('/dev/ttyS9', 'ttyS9', 'n/a'), ('/dev/ttyS8', 'ttyS8', 'n/a'),
 ('/dev/ttyS7', 'ttyS7', 'n/a'), ('/dev/ttyS6', 'ttyS6', 'n/a'),
 ('/dev/ttyS5', 'ttyS5', 'n/a'), ('/dev/ttyS4', 'ttyS4', 'n/a'),
 ('/dev/ttyS3', 'ttyS3', 'n/a'), ('/dev/ttyS2', 'ttyS2', 'n/a'),
 ('/dev/ttyS1', 'ttyS1', 'n/a'), ('/dev/ttyS0', 'ttyS0', 'n/a'),
 ('/dev/ttyUSB3', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506'),
 ('/dev/ttyUSB2', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506'),
 ('/dev/ttyUSB0', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506')]

and for

import serial.tools.list_ports;
print [port for port in serial.tools.list_ports.comports() if port[2] != 'n/a']

Result :

[('/dev/ttyUSB3', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506'),
 ('/dev/ttyUSB2', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506'),
 ('/dev/ttyUSB0', 'Huawei Technologies Co., Ltd. Modem/Networkcard ',
  'USB VID:PID=12d1:1506')]

I am study http://pyserial.readthedocs.org/en/latest/tools.html

Please help me how can get usb VID, Usb serial number etc.

Answer

Alejandro Bertinelli picture Alejandro Bertinelli · Mar 30, 2018

As @Peter said in his comment, in the newer versions of PySerial (current one is 3.4) you can get the port information easily, such as description, PID, VID, HWID, name, serial number, etc.

For example:

for port in serial.tools.list_ports.comports():
    print(port.hwid)