I was wondering if it could be possible to control the power of usb ports in Python, using vendor ids and product ids. It should be controlling powers instead of just enabling and disabling the ports. It would be appreciated if you could provide some examples.
Asked
Active
Viewed 3,846 times
2
-
What do you mean by "power" – A random coder Nov 24 '20 at 16:30
-
I meant power that is bus powered – Anthony Nov 24 '20 at 16:36
-
What's your hardware and OS? I'm pretty sure it's possible on a Raspberry Pi, probably much harder on a PC/Mac. – itaishz Nov 24 '20 at 16:43
-
I'm using Linux – Anthony Nov 24 '20 at 16:52
1 Answers
2
Look into the subprocess module in the standard library:
What commands you need will depend on the OS.
Windows
For windows you will want to look into devcon
This has been answered in previous posts
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
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'])
Nolan Foster
- 36
- 6
-
-
You can list the the usb devices using the [lsusb](https://linux.die.net/man/8/lsusb) command. This will list usb buses and the vender id. Then you can check the vender id and/or product id for each usbX with the cat command. Example: "cat /sys/bus/usb/devices/usb1/idVendor" – Nolan Foster Nov 24 '20 at 18:07
-
You can also use pyserial's [serial.tools.list_ports.comports](https://pyserial.readthedocs.io/en/latest/tools.html#serial.tools.list_ports.comports) to get vendor ids. – lead-free Jan 19 '22 at 23:17