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.
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')
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With