4

In python, given a directory or file path like /usr/local, I need to get the file system where its available. In some systems it could be / (root) itself and in some others it could be /usr.

I tried os.statvfs it doesnt help. Do I have to run the df command with the path name and extract the file system from the output? Is there a better solution?

Its for linux/unix platforms only.

Thanks

Umapathy
  • 772
  • 8
  • 21

3 Answers3

7

Here is a slightly modified version of a recipe found here. os.path.realpath was added so symlinks are handled correctly.

import os
def getmount(path):        
    path = os.path.realpath(os.path.abspath(path))
    while path != os.path.sep:
        if os.path.ismount(path):
            return path
        path = os.path.abspath(os.path.join(path, os.pardir))
    return path
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
4

Use os.stat to obtain device number of the file/directory in question (st_dev field), and then iterate through system mounts (/etc/mtab or /proc/mounts), comparing st_dev of each mount point with this number.

rkhayrov
  • 10,040
  • 2
  • 35
  • 40
2

As df itself opens and parses /etc/mtab, you could either go this way and parse this file as well (an alternative would be /proc/mounts), or you indeed parse the df output.

glglgl
  • 89,107
  • 13
  • 149
  • 217