How to find the mountpoint a file resides on?

后端 未结 8 1725
半阙折子戏
半阙折子戏 2020-12-03 17:16

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:

8条回答
  •  暖寄归人
    2020-12-03 17:59

    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
    

提交回复
热议问题