简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM