如何找到文件所在的挂载点? [英] How to find the mountpoint a file resides on?
问题描述
例如,我有一个具有以下路径的文件:
For example, I've got a file with the following path:
/media/my_mountpoint/path/to/file.txt
我已经得到了完整的路径并且想要得到:
I've got the whole path and want to get:
/media/my_mountpoint
我该怎么做?最好使用 Python 并且不使用外部库/工具.(两者都不是必需的.)
How can I do this? Preferably in Python and without using external libraries / tools. (Both are not a requirement.)
推荐答案
您可以调用 mount
命令并解析其输出以找到与您的路径相同的最长公共前缀,或者使用 stat
系统调用以获取文件所在的设备并向上爬树,直到到达不同的设备.
You may either call the mount
command and parse its output to find the longest common prefix with your path, or use the stat
system call to get the device a file resides on and go up the tree until you get to a different device.
在 Python 中,stat
可以如下使用(未经测试,可能需要扩展以处理符号链接和联合挂载等奇异的东西):
In Python, stat
may be used as follows (untested and may have to be extended to handle symlinks and exotic stuff like union mounts):
def find_mount_point(path):
path = os.path.abspath(path)
orig_dev = os.stat(path).st_dev
while path != '/':
dir = os.path.dirname(path)
if os.stat(dir).st_dev != orig_dev:
# we crossed the device border
break
path = dir
return path
编辑:直到现在我才知道 os.path.ismount
.这大大简化了事情.
Edit: I didn't know about os.path.ismount
until just now. This simplifies things greatly.
def find_mount_point(path):
path = os.path.abspath(path)
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
这篇关于如何找到文件所在的挂载点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!