I've got a backup script written in Python which creates the destination directory before copying the source directory to it. I've configured it to use /external-backup
as the destination, which is where I mount an external hard drive. I just ran the script without the hard drive being turned on (or being mounted) and found that it was working as normal, albeit making a backup on the internal hard drive, which has nowhere near enough space to back itself up.
My question is: how can I check whether the volume is mounted in the right place before writing to it? If I can detect that /external-backup
isn't mounted, I can prevent writing to it.
The bonus question is why was this allowed, when the OS knows that directory is supposed to live on another device, and what would happen to the data (on the internal hard drive) should I later mount that device (the external hard drive)? Clearly there can't be two copies on different devices at the same path!
Thanks in advance!
I would take a look at
os.path.ismount()
.For a definitive answer to something only the kernel knows for sure, ask the kernel:
That file can be read / parsed as if it was a normal file, using any tools you like. Including Python. Quick-n-dirty example:
The easiest way to check is to invoke
mount
viasubprocess
and see if it shows up there. For extra credit, useos.readlink()
on the contents of/dev/disk/by-*
to figure out which device it is.Bonus answer. If external device is not mounted data is written to root partition at path
/external-backup
. If external device is mounted data on root partition is still there but it is not reachable because/external-backup
is now pointing to external device.Old question, but I thought I'd contribute my solution (based on Dennis Williamson's and Ignacio Vazquez-Abrams's's answer) anyways. Since I'm using it on a non-Linux environment to check remote directories being mounted, /proc and mtab cannot be used and no additional checks have been implemented:
Improvements welcome!
The /etc/mtab file exists to tell you what is currently mounted. There is a
getmntent
call, but I don't think it's exported in theos
module. The quick and dirty? Open /etc/mtab and split. Ensure your device is present in column 0 and the destination mount point in column 1 is correct.