本文介绍了如何找到文件所在的安装点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

  / media / my_mountpoint / path / to / file.txt 

我得到了整个路径并希望得到:

  / media / my_mountpoint 

我该怎么做?最好在Python中,不要使用外部库/工具。 (两者都不是必需的)。

解决方案

您可以调用 mount 命令并解析其输出以找到路径中最长的公共前缀,或者使用 stat 系统调用来获取文件驻留的设备,然后上行您可以使用不同的设备。



在Python中,可以如下使用 stat (未经测试,可能必须扩展来处理符号链接和像联合坐骑这样的奇特的东西):
$ b $ pre $ def $ find $ _mount_point(path)
path = os .path.abspath(path)
orig_dev = os.stat(path).st_dev

while path!='/':
dir = os.path.dirname(path )
如果os.stat(dir).st_dev!= orig_dev:
#我们越过了设备边界
break
path = dir
返回路径

编辑:我不知道 os.path。 ismount 直到没有W上。这大大简化了事情。

  def find_mount_point(path):
path = os.path.abspath(path)
而不是os.path.ismount(路径):
path = os.path.dirname(路径)
返回路径


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

How can I do this? Preferably in Python and without using external libraries / tools. (Both are not a requirement.)

解决方案

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.

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

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

这篇关于如何找到文件所在的安装点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:54