如何在Windows中用Python控制指定USB端口实现U盘自动插拔?
Solution to Simulate USB Plug/Unplug for Test Automation
Hey there! Let's tackle your USB automation problem step by step. First, that subprocess.run error happens because this method was added in Python 3.5—if you're stuck on an older Python version, we'll use compatible alternatives. Also, keep in mind this script needs to run with administrator privileges (since enabling/disabling hardware requires elevated access).
Here's a complete, test-ready Python script that handles USB device detection, repeated plug/unplug simulation, and error handling:
import subprocess import time import re def get_devcon_output(cmd_args): """Wrapper for subprocess to work across Python versions <3.5""" try: # Use run if available (Python 3.5+) result = subprocess.run(cmd_args, capture_output=True, text=True, check=True) return result.stdout except AttributeError: # Fallback for older Python versions proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) stdout, _ = proc.communicate() return stdout.decode('utf-8', errors='ignore') def get_target_usb_hwid(target_desc="USB Mass Storage Device"): """Fetch HWID of the target USB drive (adjust target_desc as needed)""" # Run devcon to list all USB devices output = get_devcon_output(['devcon', 'hwids', '=usb']) # Parse output to find the target device's HWID hwid_pattern = re.compile(r'HWID\s*:\s*(.*)') device_blocks = output.split('\n\n') for block in device_blocks: if target_desc in block: match = hwid_pattern.search(block) if match: return match.group(1).strip() raise RuntimeError(f"Target USB device with description '{target_desc}' not found!") def toggle_usb_device(hwid, enable=True): """Enable or disable a USB device using devcon""" cmd = ['devcon', 'enable', hwid] if enable else ['devcon', 'disable', hwid] try: get_devcon_output(cmd) action = "enabled" if enable else "disabled" print(f"Successfully {action} device: {hwid}") return True except subprocess.CalledProcessError as e: print(f"Failed to {action} device: {e}") return False def simulate_usb_plug_unplug(cycles=200, delay=2): """Simulate USB plug/unplug for specified cycles""" try: # Get target USB HWID (adjust the description to match your drive) target_hwid = get_target_usb_hwid("USB Mass Storage Device") print(f"Target USB device HWID: {target_hwid}") for cycle in range(1, cycles+1): print(f"\n--- Cycle {cycle}/{cycles} ---") # Disable (unplug) if not toggle_usb_device(target_hwid, enable=False): print("Aborting cycle due to error") break time.sleep(delay) # Enable (plug back in) if not toggle_usb_device(target_hwid, enable=True): print("Aborting cycle due to error") break time.sleep(delay) print("\nUSB plug/unplug simulation completed!") except Exception as e: print(f"Error during simulation: {str(e)}") if __name__ == "__main__": # Adjust cycles and delay as needed for your test simulate_usb_plug_unplug(cycles=200, delay=1)
Key Notes for Integration:
- Devcon Setup: Make sure
devcon.exeis in your system PATH, or replace'devcon'with the full path to the executable (e.g.,r'C:\path\to\devcon.exe'). - Target Device Identification: Modify the
target_descparameter inget_target_usb_hwid()to match your USB drive's description (find it via Device Manager, or use VID/PID like'VID_XXXX&PID_XXXX'for more precision). - Permissions: Always run this script as Administrator—right-click your Python IDE/terminal and select "Run as administrator".
- Python Version Compatibility: The
get_devcon_output()function handles both Python 3.5+ (usingsubprocess.run) and older versions (falling back tosubprocess.Popen). - Test Adjustments: Tweak the
cyclesanddelayparameters to match your test requirements (shorter delay for faster cycles, longer delay if the system needs time to recognize the device).
Troubleshooting Tips:
- If
devconthrows "No matching devices found", double-check your target device description or HWID. - Permission errors? Ensure you're running the script with elevated privileges.
- Device not re-enabling? Increase the
delayto give the system time to process the disable/enable commands.
内容的提问来源于stack exchange,提问作者root
相关产品推荐
相关产品推荐

