Detecting USB Insertion/Removal using Python

In my last blog, i wrote about how usbmount can be used to automatically mount a usb. Today, i had to detect this mounting from python and show it in a web application that a usb has been inserted. I used pyudev for this and ran it in a different thread so that the main application thread is not affected by pyudev’s monitor loop.

class USBDetector():
    ''' Monitor udev for detection of usb '''

    def __init__(self):
        ''' Initiate the object '''
        thread = threading.Thread(target=self._work)
        thread.daemon = True

    def _work(self):
        ''' Runs the actual loop to detect the events '''
        self.context = pyudev.Context()
        self.monitor = pyudev.Monitor.from_netlink(self.context)
        # this is module level logger, can be ignored"Starting to monitor for usb")
        for device in iter(self.monitor.poll, None):
  "Got USB event: %s", device.action)
            if device.action == 'add':
                # some function to run on insertion of usb
                # some function to run on removal of usb

Since, usbmount mounts the filesystem of usb at some particular locations (/media/usb0-7), you can easily check for files in those folders and do whatever you wish to do with it.

Using the above code would be as easy as creating an object of USBDetector class.