Python:获取 Windows 或 Linux 的挂载点

5 投票
3 回答
12411 浏览
提问于 2025-04-15 12:57

我需要一个函数来判断一个文件夹是否是某个驱动器的挂载点。
我找到了一段在Linux上运行得不错的代码:

def getmount(path):
  path = 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

但是我不太确定在Windows上该怎么做。我可以直接认为挂载点就是驱动器的字母(比如C:)吗?我觉得在Windows上也可以有网络挂载,所以我希望能检测到这种挂载。

3 个回答

0

这里有一些代码,可以返回由驱动器字母指向的UNC路径。我想可能有更简单的方法来做到这一点,但我还是想贡献我的一点小代码。

import sys,os,string,re,win32file
for ch in string.uppercase:  # use all uppercase letters, one at a time
    dl = ch + ":"
    try:
        flds = win32file.QueryDosDevice(dl).split("\x00")
    except:
        continue
    if re.search('^\\\\Device\\\\LanmanRedirector\\\\',flds[0]):
        flds2 = flds[0].split(":")
    st = flds2[1]
    n = st.find("\\")
    path = st[n:] 
        print(path)
3

你是想找出挂载点,还是只是想确认它是否是一个挂载点呢?

不管怎样,正如上面提到的,在Windows XP系统中,可以把一个逻辑驱动器映射到一个文件夹里。

想了解更多细节,可以查看这里: http://www.modzone.dk/forums/showthread.php?threadid=278

我建议你试试win32api.GetVolumeInformation这个方法。

>>> import win32api
>>> win32api.GetVolumeInformation("C:\\")
    ('LABEL', 1280075370, 255, 459007, 'NTFS')
>>> win32api.GetVolumeInformation("D:\\")
    ('CD LABEL', 2137801086, 110, 524293, 'CDFS')
>>> win32api.GetVolumeInformation("C:\\TEST\\") # same as D:
    ('CD LABEL', 2137801086, 110, 524293, 'CDFS')
>>> win32api.GetVolumeInformation("\\\\servername\\share\\")
    ('LABEL', -994499922, 255, 11, 'NTFS')
>>> win32api.GetVolumeInformation("C:\\WINDOWS\\") # not a mount point
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    pywintypes.error: (144, 'GetVolumeInformation', 'The directory is not a subdirectory of the root directory.')
3

以前,Windows并不称这些为“挂载点”[编辑:现在是这样称呼的,见下文!]。通常你会看到两种传统的写法,一种是驱动器字母,比如 Z:,另一种是 \\hostname(前面有两个反斜杠:要小心处理,或者在Python中使用 r'...' 这种写法来表示这样的字符串)。

编辑:自从NTFS 5.0开始,挂载点得到了支持,但根据这篇文章,它们的API状态相当糟糕——文章标题说是“损坏且文档不全”。也许执行微软提供的mountvol.exe是最简单的方法——mountvol drive:path /L应该会显示指定路径的挂载卷名称,或者直接用 mountvol 来列出所有这样的挂载(我说“应该”是因为我现在无法检查)。你可以用 subprocess.Popen 来执行它,并查看它的输出。

撰写回答