如何 运行 Python 中的 PowerShell cmdlet 获取连接的 USB 设备列表?
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)
使用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.
我对 Python 的拙劣理解,我想如果您想使用 PowerShell 生成的输出,您可能需要 序列化 对象和 de-serialize 它们在 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')
我尝试在我的 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)
使用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.
我对 Python 的拙劣理解,我想如果您想使用 PowerShell 生成的输出,您可能需要 序列化 对象和 de-serialize 它们在 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')