在Python中控制USB端口的电源

Ant*_*ony 6 python usb port libusb pyusb

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

小智 4

查看标准库中的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

Run Code Online (Sandbox Code Playgroud)

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

Run Code Online (Sandbox Code Playgroud)