Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a PowerShell cmdlet in Python to get a list of connected USB devices?

I try to list connected USB devices in my Python project.

I tried to use os.system() with a command prompt but I cannot find a command for command prompt to list connected USB devices (names).

I found a PowerShell command which is

Get-PnpDevice -PresentOnly | Where-Object { $_. InstanceId -match '^USB' }

That works fine.

I want to know if there is either a command prompt to list USB connected devices with os.system() or how to run the PowerShell cmdlet in Python using os.system() or any other command.

like image 529
Omar Moustafa Avatar asked Oct 26 '25 08:10

Omar Moustafa


2 Answers

There is a module called pyUSB that works really well.
Alternatively, to run Powershell commands, you can use the subprocess package.

import subprocess
result = subprocess.run(["powershell", "-Command", MyCommand], capture_output=True)

My poor take at Python, I guess if you want to work with the output produced by PowerShell you might want to serialize the objects and de-serialize them in Python, hence the use of ConvertTo-Json.

import subprocess
import json

cmd = '''
    Get-PnpDevice -PresentOnly |
        Where-Object { $_.InstanceId -match '^USB' } |
            ConvertTo-Json
'''

result = json.loads(
    subprocess.run(["powershell", "-Command", cmd], capture_output=True).stdout
)

padding = 0
properties = []

for i in result[0].keys():
    if i in ['CimClass', 'CimInstanceProperties', 'CimSystemProperties']:
        continue
    properties.append(i)
    if len(i) > padding:
        padding = len(i)

for i in result:
    for property in properties:
        print(property.ljust(padding), ':', i[property])
    print('\n')
like image 38
Santiago Squarzon Avatar answered Oct 28 '25 20:10

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!