Basj
Basj

Reputation: 46351

Detect when new USB device is connected (plug'n'play)

Using this answer, we are able to query all the USB devices connected at a precise moment.

I have a Python program running on Linux (Debian or RaspBian) that does a specific task, but I also want that this program listens if new USB device is connected, and when this happens, trigger a specific action.

I'm thinking about doing a new thread that does:

while True:
  list_USB_devices()   # using https://stackoverflow.com/a/8265634/1422096
  see_if_new_devices_in_this_list()
  time.sleep(2)        # wait 2 seconds

but I don't find this solution very elegant.

What's a cleaner solution to detect in the background of a Python program if a new USB device is connected?

Example of application for my program: listen if a new USB-MIDI keyboard/device is connected, and if so, attach it with rtmidi-python "Plug and play!"

Upvotes: 0

Views: 2193

Answers (1)

jcoppens
jcoppens

Reputation: 5440

Look into the gio library (part of glib). You can attach watches and connect callbacks when devices are created. This way you don't have to poll at all. Set a watch on the devices directory, look for file creation. Filter out files not interested in.

You can probably also look at 'udev' system itself, and write a rule to execute something on apparition of a new usb device.

Upvotes: 1

Related Questions