代码之家  ›  专栏  ›  技术社区  ›  noahd

python:在Windows或Linux上获取挂载点

  •  5
  • noahd  · 技术社区  · 16 年前

    我需要一个函数来确定目录是否是驱动器的装入点。 我发现这个代码在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 回复  |  直到 10 年前
        1
  •  3
  •   Alex Martelli    16 年前

    Windows没有使用它们来调用“挂载点”[ 编辑 :现在可以了,见下文!]和两个典型的/传统的语法,你可以找到他们要么是驱动器号,例如。 Z: 否则 \\hostname (带两个前反斜杠:小心逃生或使用 r'...' python fpr中的符号。

    编辑 :因为支持NTFS 5.0安装点,但是根据 this post 这篇文章的标题是:“它们的API处于一种相当的状态——”被破坏了,文档也不完整“。可能执行微软提供的 mountvol.exe 是最不痛苦的方式-- mountvol drive:path /L 应发出指定路径的已装入卷名,或 mountvol 列出所有这些坐骑(我必须说“应该”,因为我现在不能检查)。你可以用 subprocess.Popen 并检查其输出。

        2
  •  3
  •   Mark    16 年前

    您想查找装入点还是只确定它是装入点?

    无论如何,如上所述,在WinXP中可以将逻辑驱动器映射到文件夹。

    详情请参见此处: 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
  •  0
  •   Kevin Buchs    14 年前

    下面是一些返回驱动器号指向的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)