Detecting insertion/removal of USB input devices on Windows 10 running in VirtualBox

坚强是说给别人听的谎言 提交于 2021-01-27 13:37:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!