Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve list of USB items using Python

Tags:

python

How can I retrieve the items plugged into the computer through USB using python? I've searched around on here and found some old examples which don't appear to work anymore as they are over 5 years old.

I would like an example where I can list the names seen in the image below which is a screenshot of the Device Manager.

enter image description here

The code below lists all the USB devices but none of the data returns the Names seen in the image, why is that?

import win32com.client
import pprint

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    # print usb.DeviceID
    # pprint.pprint (dir(usb))
    # pprint.pprint (vars(usb))
    # print usb.__dict__
    print ('Device ID:', usb.DeviceID)
    print ('Name:', usb.name)
    print ('System Name:', usb.SystemName)
    print ('Caption:', usb.Caption)
    print ('Caption:', usb.Caption)
    print ('ClassCode:', usb.ClassCode)
    print ('CreationClassName:', usb.CreationClassName)
    print ('CurrentConfigValue:', usb.CurrentConfigValue)
    print ('Description:', usb.Description)
    print ('PNPDeviceID:', usb.PNPDeviceID)
    print ('Status:', usb.Status)
    print ('\n')
like image 557
JokerMartini Avatar asked Jan 31 '17 14:01

JokerMartini


People also ask

Which command is used to obtain a list of USB devices?

The widely used lsusb command can be used to list all the connected USB devices in Linux. As you can see from the output of the lsusb command in the screenshot below, all the connected USB device is listed. The Bus ID, Device ID, USB ID, and a title is displayed in the output of lsusb command.

What does Lsusb show?

The lsusb command in Linux is used to display the information about USB buses and the devices connected to them. The properties displayed are speed, BUS, class, type details, etc.


1 Answers

I would install pyserial

py -m pip install pyserial

and use serial.tools.list_ports. You can execute it as a module:

py -m serial.tools.list_ports

or incorporate the module and its corresponding methods into your code base:

import serial
from serial.tools import list_ports

if __name__ == "__main__":
    for port in list_ports.comports():
        if "USB" in port.hwid:
            print(f"Name: {port.name}")
            print(f"Description: {port.description}")
            print(f"Location: {port.location}")
            print(f"Product: {port.product}")
            print(f"Manufacturer: {port.manufacturer}")
            print(f"ID: {port.pid}")

More information can be found here:

pyserial docs >> tools

like image 140
A. Hendry Avatar answered Nov 17 '22 00:11

A. Hendry