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 ha开发者_运维知识库ve 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
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
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.
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.
精彩评论