问题
I once again already have some working Python code to detect the insertion/removal of specific USB device types in Windows 10 (from here).
import wmi
device_connected_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
device_disconnected_wql = "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
c = wmi.WMI()
connected_watcher = c.watch_for(raw_wql=device_connected_wql)
disconnected_watcher = c.watch_for(raw_wql=device_disconnected_wql)
while 1:
try:
connected = connected_watcher(timeout_ms=10)
except wmi.x_wmi_timed_out:
pass
else:
if connected:
print("Keyboard connected")
try:
disconnected = disconnected_watcher(timeout_ms=10)
except wmi.x_wmi_timed_out:
pass
else:
if disconnected:
print("Keyboard disconnected")
I wanted to use this code in a Python script that runs on Windows 10 in VirtualBox 6.0.22 on Ubuntu 18.04 (x64). VirtualBox Guest Additions are installed.
Unfortunately this script does not work, because it does not display any message when a USB keyboard is inserted or removed. Does the VirtualBox configuration need to be changed for this?
However, the following error appears when exiting the script:
Process finished with exit code -1
回答1:
Firstly, instead of while 1:
, use While True:
. Then, make sure that your USB drive is configured correctly in VirtualBox (this link may help). And what I found for Process finished with exit code -1
is all related to PyCharm, idk if you are using this. Hope this helps.
来源:https://stackoverflow.com/questions/61856614/detecting-insertion-removal-of-usb-input-devices-on-windows-10-running-in-virtua