使用Python确定子目录是否在装入的文件系统上

时间:2015-08-11 04:15:03

标签: python path

在此路径中,目录' foo'安装在外部文件系统上。目录' bar'是&f;'。

的子目录
'/Volumes/foo/bar'

使用os.path.ismount('/Volumes/foo'),我可以正确地确定' foo'确实是一个外部装载。但是,使用os.path.ismount('/Volumes/foo/bar')' bar'正确地确定它没有安装在外部。

所以,我的问题是,我怎样才能正确地确定' bar'是外部安装的文件系统的子目录?我需要能够确定不同深度的许多目录。任何线索都会很棒!

2 个答案:

答案 0 :(得分:1)

来自文档:

  

如果路径名路径是装载

,则返回True
强调我的。 mount指向目录的子目录位于装载驱动器上,但不是装载"点"。

  

我怎样才能正确地确定' bar'是外部安装的文件系统的子目录?

在这种情况下,我将遍历父层次结构,直到我到达根目录,或者我点击了一个挂载点。以先到者为准。

假设有一个Unix类型的文件系统:

def is_on_mount(path):
  while True:
    if path == os.path.dirname(path):
      # we've hit the root dir
      return False
    elif os.path.ismount(path):
      return True
    path = os.path.dirname(path)

path = '/mount/one/two/three'
is_on_mount(path)

答案 1 :(得分:0)

import os
import subprocess


def is_on_mounted_volume(path):
    try:
        df = subprocess.check_output(['df', path]).split('\n')
        mountpoint = df[1].split()[-1][0]
        return os.path.ismount(mountpoint)
    except subprocess.CalledProcessError:
        pass