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

Time:05-23

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.

CodePudding user response:

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)

CodePudding user response:

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
)

for i in result:
    print('\n')
    for key in i.keys():
        if key in ['CimClass', 'CimInstanceProperties', 'CimSystemProperties']:
            continue
        print(key.ljust(40), ':', i[key])

CodePudding user response:

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.
  • Related