从路径在Python中确定文件系统类型

6 投票
5 回答
7100 浏览
提问于 2025-04-18 17:07

有没有什么便携的方法可以在Python(2.*)中获取包含某个路径的设备的文件系统类型?比如说,像下面这样的:

>>> get_fs_type("/foo/bar")
'vfat'

5 个回答

-1

对于那些重视简洁的人,这里有一个稍微简短一点的版本,来自 gena2x 的回答:

def get_fs_type(path):
    path_matching_fstypes_mountpoints = [
        part for part in disk_partitions() 
        if str(path.resolve()).startswith(part.mountpoint)
    ]
    return sorted(path_matching_fstypes_mountpoints, key=lambda x: len(x.mountpoint))[-1].fstype
1

在Linux系统上安装stat命令时,我使用了

P = subprocess.run(['stat', '-f', '-c', '%T', path],
                    capture_output=True, text=True)
fstype = P.stdout.strip().lower()

补充说明:如果加上text=True,返回的结果会是str类型的字符串,否则返回的是bytes类型的字节数据。另外,你可能还想检查一下P.returncode == 0,这表示命令是否成功执行。此外,如果这个代码经常被调用,你可以考虑使用functools.cache来缓存结果,这样可以提高效率。

1

在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常会把它们转换成一种特定的格式。

比如说,如果你有一个数字字符串“123”,但是程序需要的是数字类型的123,那么你就需要把这个字符串转换成数字。这种转换的过程就叫做“类型转换”。

类型转换有很多种方式,最常见的就是把字符串转换成数字,或者把数字转换成字符串。不同的编程语言有不同的方法来实现这些转换。

在处理数据时,确保你使用的类型是正确的,这样程序才能正常运行,不会出现错误。

import psutil

def get_fs_type(path):
    bestMatch = ""
    fsType = ""
    for part in psutil.disk_partitions():
        if mypath.startswith(part.mountpoint) and len(bestMatch) < len(part.mountpoint):
            fsType = part.fstype
            bestMatch = part.mountpoint
    return fsType
3

感谢用户3012759的评论,这里有一个解决方案(虽然可以改进,但确实有效):

import psutil

def get_fs_type(mypath):
    root_type = ""
    for part in psutil.disk_partitions():
        if part.mountpoint == '/':
            root_type = part.fstype
            continue

        if mypath.startswith(part.mountpoint):
            return part.fstype

    return root_type

在GNU/Linux系统中,对于"/"需要单独处理,因为所有的(绝对)路径都是以这个符号开头的。

下面是代码在GNU/Linux系统中“运行”的一个例子:

>>> get_fs_type("/tmp")
'ext4'
>>> get_fs_type("/media/WALKMAN")
'vfat'

还有一个在Windows系统下的例子(如果有必要的话,是XP版):

>>> get_fs_type("C:\\")  # careful: "C:" will yield ''
'NTFS'
4

这是我的解决方案。我试着让它更通用,以便在 /var/lib 是不同分区的情况下也能使用。不过,代码里出现了一些小问题,因为在 Windows 系统中,挂载点的后面总是有一个分隔符,而在 Linux 系统中则没有。这就意味着需要同时测试这两种情况。

import psutil, os
def printparts():
    for part in psutil.disk_partitions():
        print part
def get_fs_type(path):
    partition = {}
    for part in psutil.disk_partitions():
        partition[part.mountpoint] = (part.fstype, part.device)
    if path in partition:
        return partition[path]
    splitpath = path.split(os.sep)  
    for i in xrange(len(splitpath),0,-1):
        path = os.sep.join(splitpath[:i]) + os.sep
        if path in partition:
            return partition[path]
        path = os.sep.join(splitpath[:i])
        if path in partition:
            return partition[path]
    return ("unkown","none")

printparts()

for test in ["/", "/home", "/var", "/var/lib", "C:\\", "C:\\User", "D:\\"]:
    print "%s\t%s" %(test, get_fs_type(test))

在 Windows 系统上:

python test.py
sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed')
sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed')
sdiskpart(device='E:\\', mountpoint='E:\\', fstype='NTFS', opts='rw,fixed')
sdiskpart(device='F:\\', mountpoint='F:\\', fstype='', opts='cdrom')
sdiskpart(device='G:\\', mountpoint='G:\\', fstype='', opts='cdrom')
/       ('unkown', 'none')
/home   ('unkown', 'none')
/var    ('unkown', 'none')
/var/lib        ('unkown', 'none')
C:\     ('NTFS', 'C:\\')
C:\User ('NTFS', 'C:\\')
D:\     ('NTFS', 'D:\\')

在 Linux 系统上:

python test.py
partition(device='/dev/cciss/c0d0p1', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro')
partition(device='/dev/cciss/c0d1p3', mountpoint='/home', fstype='ext4', opts='rw')
partition(device='/dev/cciss/c0d1p2', mountpoint='/var', fstype='ext4', opts='rw')
/       ('ext4', '/dev/cciss/c0d0p1')
/home   ('ext4', '/dev/cciss/c0d1p3')
/var    ('ext4', '/dev/cciss/c0d1p2')
/var/lib        ('ext4', '/dev/cciss/c0d1p2')
C:\     ('unkown', 'none')
C:\User ('unkown', 'none')
D:\     ('unkown', 'none')

撰写回答