Python: Get Mount Point on Windows or Linux

后端 未结 3 1044
说谎
说谎 2021-01-05 23:28

I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux:

def getmount(path):
  path          


        
相关标签:
3条回答
  • 2021-01-06 00:08

    Windows didn't use to call them "mount points" [edit: it now does, see below!], and the two typical/traditional syntaxes you can find for them are either a drive letter, e.g. Z:, or else \\hostname (with two leading backslashes: escape carefully or use r'...' notation in Python fpr such literal strings).

    edit: since NTFS 5.0 mount points are supported, but according to this post the API for them is in quite a state -- "broken and ill-documented", the post's title says. Maybe executing the microsoft-supplied mountvol.exe is the least painful way -- mountvol drive:path /L should emit the mounted volume name for the specified path, or just mountvol such list all such mounts (I have to say "should" because I can't check right now). You can execute it with subprocess.Popen and check its output.

    0 讨论(0)
  • 2021-01-06 00:28

    Here is some code to return the UNC path pointed to by a drive letter. I suppose there is a more slick way to do this, but I thought I'd contribute my small part.

    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)
    
    0 讨论(0)
  • 2021-01-06 00:32

    Do you want to find the mount point or just determine if it is a mountpoint?

    Regardless, as commented above, it is possible in WinXP to map a logical drive to a folder.

    See here for details: http://www.modzone.dk/forums/showthread.php?threadid=278

    I would try 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.')
    
    0 讨论(0)
提交回复
热议问题