1
votes

In my Python program I need to constantly check if a new USB drive is connected to my device, running x86 Linux (Ubuntu). Other USB devices should not be mistaken for a USB-drive, such as keyboards, mouses, or anything else. What is the best way to do this?

In my particular case I have a custom media player device powered by a x86 single board PC running Linux.

1

1 Answers

1
votes

Most linux systems already have some mechanism which detects new usb devices and automatically mounts them if they are storage devices, and so on. What you can do is use python's interface to the inotify library to monitor /mnt or /dev.

To see how it works, install inotify-tools or some similar named package and you can do:

$ inotifywait -m -e create /tmp &

This command monitors (-m) /tmp for the creation (-e create) of new files or directories. Eg touch /tmp/x and it will output

/tmp/ CREATE x

You can do the same from python and its python-inotify or similar package. There is the pyinotify command, but more usefully you can code the equivalent python program:

import pyinotify
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm)
wm.add_watch('/tmp', pyinotify.IN_CREATE)
notifier.loop()

When you rm and recreate /tmp/x this prints:

<Event dir=False mask=0x100 maskname=IN_CREATE name=x path=/tmp pathname=/tmp/x wd=1 >

See the wiki for a tutorial etc.


In your case you can monitor /mnt to detect newly mounted filesystems, or /dev to discover new devices like /dev/sdb and /dev/sdb1. Inotify is not recursive, so only changes directly in the watched directory are returned.