简体   繁体   中英

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!"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM