首页 > 解决方案 > 在 Python 中控制 USB 端口的电源

问题描述

我想知道是否可以使用供应商 ID 和产品 ID 在 Python 中控制 USB 端口的功能。它应该控制电源,而不仅仅是启用和禁用端口。如果您能提供一些示例,我们将不胜感激。

标签: pythonusbportlibusbpyusb

解决方案


查看标准库中的subprocess模块:

您需要什么命令取决于操作系统。

视窗

对于 Windows,您将需要查看devcon

这个已经在之前的帖子里回答过了

import subprocess
# Fetches the list of all usb devices:
result = subprocess.run(['devcon', 'hwids', '=usb'], 
    capture_output=True, text=True)

# ... add code to parse the result and get the hwid of the device you want ...

subprocess.run(['devcon', 'disable', parsed_hwid]) # to disable
subprocess.run(['devcon', 'enable', parsed_hwid]) # to enable

Linux

查看有关 shell 命令的帖子

import subprocess

# determine desired usb device

# to disable
subprocess.run(['echo', '0', '>' '/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms']) 
subprocess.run(['echo', 'auto', '>' '/sys/bus/usb/devices/usbX/power/control']) 
# to enable
subprocess.run(['echo', 'on', '>' '/sys/bus/usb/devices/usbX/power/control']) 


推荐阅读