How to detect a new usb device is connected on python

Harel2320 picture Harel2320 · Nov 26, 2017 · Viewed 22k times · Source

I want to make something which will run on the background and only after the computer detect new device is connected the rest of the code will run, is there any elegant way to do such a thing?

Answer

ralf htp picture ralf htp · Nov 28, 2017

this is operating system dependent

in linux you can use pyudev for this :

Almost the complete libudev functionality is exposed. You can:

  • Enumerate devices, filtered by specific criteria (pyudev.Context)
  • Query device information, properties and attributes,
  • Monitor devices, both synchronously and asynchronously with background threads, or within the event loops of Qt (pyudev.pyqt4, pyudev.pyside), glib (pyudev.glib) and wxPython (pyudev.wx).

https://pyudev.readthedocs.io/en/latest/

source code is in http://pyudev.readthedocs.io/en/v0.14/api/monitor.html, see the receive_device() function

in windows you can use the WMI ( Windows Management Instrumentation ) like in https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/ ( Python Read the Device Manager Information ) or a python binding like in https://pypi.python.org/pypi/infi.devicemanager