从Python中的路径确定文件系统类型 [英] Determining the filesystem type from a path in Python

查看:170
本文介绍了从Python中的路径确定文件系统类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python(2. *)中是否有任何便携式方法来获取包含给定路径的设备的文件系统类型?例如,类似:

Is there any portable way in Python (2.*) to obtain the filesystem type of the device containing a given path? For instance, something like:

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

推荐答案

这是我的解决方案.我试图使它在/var/lib是不同分区的情况下更通用.代码中有些难看,因为Windows始终在安装点的末尾带有分隔符,而在Linux中则省略了该分隔符.这意味着要同时测试它们

Here is my solution. I tried to make it more generic for cases where /var/lib is a different partition. Some ugliness crept in the code as windows always has the separator at the end of the mountpoint, while this is omitted in linux. Which means testing them both

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')

这篇关于从Python中的路径确定文件系统类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆