Following up on @Mark Setchell's udev and @MarkR's select suggestions, first make sure that the card will be automounted with an /etc/fstab
entry similar to:
/dev/sdb1 /mnt/card extfat-fuse ro,defaults,nofail,user,auto 0 0
udev
A simple solution is to create a udev rule in /etc/udev/rules.d/99-local.rules
:
ACTION=="add", KERNEL="sdb*", SUBSYSTEM=="block", RUN+="/bin/bash -c '/bin/date >> /tmp/udev.txt'"
The RUN
script is run as root and it must complete quickly. The solution is global to the RaspberryPi. Outcomes can be tough to debug. The mounted file system might not be ready by the time the rule is executed.
select
Python's select module exposes POSIX and other OS-specific system calls to monitor I/O. One has to be a little careful in that neither the mounted directory nor the /proc/mounts
files behave like regular files, so the utility of update times and tools like watchdog are limited.
import select
f = open('/proc/self/mounts')
pollster = select.poll()
pollster.register(f, select.POLLERR | select.POLLPRI)
events = pollster.poll(60*1000)
The pollster.poll(60*1000)
call here will wait up to 60 seconds and return a list with pairs of file descriptor and event ids. If the list is non-empty, you can grep /proc/self/mounts
for your mount point to act or poll again.
Using select might be more complex than udev, but it doesn't require root and it's simpler to debug. It does, however, require you ensure your polling always runs and to implement logic to handle updates.