Omar Moustafa
Omar Moustafa

Reputation: 111

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.

Upvotes: 4

Views: 966

Answers (3)

Santiago Squarzon
Santiago Squarzon

Reputation: 60718

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')

Upvotes: 1

Andrey Naradzetski
Andrey Naradzetski

Reputation: 49

Use subprocess module. In your case it will look like:

import subprocess

devices_raw: str = subprocess.run(
    ["Get-PnpDevice -PresentOnly | Where-Object { $_. InstanceId -match '^USB' }"],
    capture_output=True
).stdout

# ... working with devices_raw as a string, probably you'll need to split it or smth.

Upvotes: -1

Florentin Labelle
Florentin Labelle

Reputation: 70

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)

Upvotes: 2

Related Questions