How can I check whether a volume is mounted where it is supposed to be using Python?
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:
cat /proc/mounts
That file can be read / parsed as if it was a normal file, using any tools you like. Including Python. Quick-n-dirty example:
#!/usr/bin/python
d = {}
for l in file('/proc/mounts'):
if l[0] == '/':
l = l.split()
d[l[0]] = l[1]
import pprint
pprint.pprint(d)
The easiest way to check is to invoke mount
via subprocess
and see if it shows up there. For extra credit, use os.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:
def is_mounted(special, directory):
search_prefix = '{} on {}'.format(special, directory.rstrip('/'))
if os.path.ismount(directory):
mounts = subprocess.check_output(['mount']).split('\n')
for line in mounts:
if line[:len(search_prefix)] == search_prefix:
return True;
return False
Improvements welcome!