[英]How to run a PowerShell cmdlet in Python to get a list of connected USB devices?
我尝试在我的 Python 项目中列出连接的 USB 设备。
我尝试将os.system()
与命令提示符一起使用,但我找不到命令提示符列出连接的 USB 设备(名称)的命令。
我找到了一个 PowerShell 命令
Get-PnpDevice -PresentOnly | Where-Object { $_. InstanceId -match '^USB' }
这很好用。
我想知道是否有使用os.system()
列出 USB 连接设备的命令提示符,或者如何使用os.system()
或任何其他命令在 Python 中运行 PowerShell cmdlet。
有一个名为pyUSB的模块运行良好。
或者,要运行 Powershell 命令,您可以使用subprocess包。
import subprocess
result = subprocess.run(["powershell", "-Command", MyCommand], capture_output=True)
我对 Python 的看法很差,我想如果你想使用 PowerShell 生成的输出,你可能想在 Python 中序列化对象并反序列化它们,因此使用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')
使用subprocess
模块。 在你的情况下,它看起来像:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.