3

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

Atalanttore
  • 349
  • 5
  • 22

1 Answers1

3

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.

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Hugo LB
  • 158
  • 5
  • Many thanks for your tips. Unfortunately VirtualBox on my Ubuntu system does not show any connected USB devices to choose from (unlike as described in the link). – Atalanttore Jun 20 '20 at 12:34