How can I check whether a volume is mounted where it is supposed to be using Python?

Solution 1:

I would take a look at os.path.ismount().

Solution 2:

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)

Solution 3:

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.


Solution 4:

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.


Solution 5:

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!