【问题标题】:Find size and free space of the filesystem containing a given file查找包含给定文件的文件系统的大小和可用空间
【发布时间】:2011-05-14 16:36:39
【问题描述】:

我在 Linux 上使用 Python 2.6。最快的方法是什么:

  • 确定哪个分区包含给定的目录或文件?

    例如,假设/dev/sda2 挂载在/home 上,/dev/mapper/foo 挂载在/home/foo 上。从字符串"/home/foo/bar/baz" 我想恢复("/dev/mapper/foo", "home/foo") 对。

  • 然后,获取给定分区的使用统计信息?例如,给定/dev/mapper/foo,我想获取分区的大小和可用空间(以字节为单位或大约以兆字节为单位)。

【问题讨论】:

  • 您是否考虑了符号链接?虽然您可能有 /home 和 /mnt/somedisk ,但 /home/foo/x 可能是目录 /mnt/somedisk/xyzzy 的符号链接 - 所以它出现在 /home 下,但实际上位于 /mnt/somedisk
  • @Piskvor:不——暂时我不需要关注符号链接,它们只是普通的目录。第一个问题基本上是问“找到最近的安装了分区的祖先目录”。

标签: python linux filesystems diskspace vfs


【解决方案1】:

在Linux中通常/proc目录包含这样的信息,它是一个虚拟文件系统。例如,/proc/mounts 提供有关当前已安装磁盘的信息;你可以直接解析它。 top、df 等实用程序都使用了/proc。

我没用过,但如果你想要一个包装器,这也可能有帮助:http://bitbucket.org/chrismiles/psi/wiki/Home

【讨论】:

    【解决方案2】:

    如果您只需要设备上的可用空间,请使用下面的os.statvfs() 查看答案。

    如果您还需要与文件关联的设备名称和挂载点,则应调用外部程序来获取此信息。 df 将提供您需要的所有信息——当调用 df filename 时,它会打印一行关于包含该文件的分区的信息。

    举个例子:

    import subprocess
    df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
    output = df.communicate()[0]
    device, size, used, available, percent, mountpoint = \
        output.split("\n")[1].split()
    

    请注意,这相当脆弱,因为它取决于 df 输出的确切格式,但我不知道有更强大的解决方案。 (有一些依赖于下面/proc 文件系统的解决方案比这个更不便携。)

    【讨论】:

    • 具体来说他可以做import命令,然后commands.getoutput("df filename | tail -1 | gawk '{ print $6 }' ")
    • commands 模块被subprocess 取代。当我可以在 Python 中进行输出解析时,我不会在 bash 中进行输出解析:)
    • 我不知道 df 的“文件名”参数。 “df -B MB 文件名”就可以了。非常感谢。
    • 这种方法并不总是有效。在我的环境中,输出消耗不止一行。在这种情况下,脚本会得到ValueError('need more than 5 values to unpack',因为设备列和其他信息位于不同的行中。
    • @liuyix 这个答案适用于 Linux 和来自 GNU coreutils 的 df。如果您不需要设备名称和挂载点,请使用下一个答案中的代码。
    【解决方案3】:

    对于第一点,您可以尝试使用os.path.realpath 获取规范路径,对照/etc/mtab 检查它(我实际上建议调用getmntent,但我找不到正常的访问方式) 找到最长的匹配。 (可以肯定的是,您可能应该 stat 文件和假定的挂载点来验证它们实际上是否在同一设备上)

    对于第二点,使用os.statvfs获取块大小和使用信息。

    (免责声明:我没有测试过这些,我所知道的大部分来自 coreutils 来源)

    【讨论】:

    • re getmntent:嗯,import ctypes; ctypes.cdll.LoadLibrary("libc.so.6").getmntent 的可能性总是存在的,但并不是那么简单……
    • 我很好奇为什么这会被否决,评论会很感激
    【解决方案4】:
    import os
    
    def get_mount_point(pathname):
        "Get the mount point of the filesystem containing pathname"
        pathname= os.path.normcase(os.path.realpath(pathname))
        parent_device= path_device= os.stat(pathname).st_dev
        while parent_device == path_device:
            mount_point= pathname
            pathname= os.path.dirname(pathname)
            if pathname == mount_point: break
            parent_device= os.stat(pathname).st_dev
        return mount_point
    
    def get_mounted_device(pathname):
        "Get the device mounted at pathname"
        # uses "/proc/mounts"
        pathname= os.path.normcase(pathname) # might be unnecessary here
        try:
            with open("/proc/mounts", "r") as ifp:
                for line in ifp:
                    fields= line.rstrip('\n').split()
                    # note that line above assumes that
                    # no mount points contain whitespace
                    if fields[1] == pathname:
                        return fields[0]
        except EnvironmentError:
            pass
        return None # explicit
    
    def get_fs_freespace(pathname):
        "Get the free space of the filesystem containing pathname"
        stat= os.statvfs(pathname)
        # use f_bfree for superuser, or f_bavail if filesystem
        # has reserved space for superuser
        return stat.f_bfree*stat.f_bsize
    

    我电脑上的一些示例路径名:

    path 'trash':
      mp /home /dev/sda4
      free 6413754368
    path 'smov':
      mp /mnt/S /dev/sde
      free 86761562112
    path '/usr/local/lib':
      mp / rootfs
      free 2184364032
    path '/proc/self/cmdline':
      mp /proc proc
      free 0
    

    PS

    如果在 Python ≥3.3 上,则有 shutil.disk_usage(path),它返回以字节表示的 (total, used, free) 的命名元组。

    【讨论】:

    • 如上所述:我刚刚在带有 ubifs 的嵌入式系统上使用 statvfs 的这种方法失败了。它产生了 100MB 的免费空间,其中只有 10 个可用。我不确定 100 是从哪里来的。
    【解决方案5】:

    这应该可以满足您的所有要求:

    import os
    from collections import namedtuple
    
    disk_ntuple = namedtuple('partition',  'device mountpoint fstype')
    usage_ntuple = namedtuple('usage',  'total used free percent')
    
    def disk_partitions(all=False):
        """Return all mountd partitions as a nameduple.
        If all == False return phyisical partitions only.
        """
        phydevs = []
        f = open("/proc/filesystems", "r")
        for line in f:
            if not line.startswith("nodev"):
                phydevs.append(line.strip())
    
        retlist = []
        f = open('/etc/mtab', "r")
        for line in f:
            if not all and line.startswith('none'):
                continue
            fields = line.split()
            device = fields[0]
            mountpoint = fields[1]
            fstype = fields[2]
            if not all and fstype not in phydevs:
                continue
            if device == 'none':
                device = ''
            ntuple = disk_ntuple(device, mountpoint, fstype)
            retlist.append(ntuple)
        return retlist
    
    def disk_usage(path):
        """Return disk usage associated with path."""
        st = os.statvfs(path)
        free = (st.f_bavail * st.f_frsize)
        total = (st.f_blocks * st.f_frsize)
        used = (st.f_blocks - st.f_bfree) * st.f_frsize
        try:
            percent = ret = (float(used) / total) * 100
        except ZeroDivisionError:
            percent = 0
        # NB: the percentage is -5% than what shown by df due to
        # reserved blocks that we are currently not considering:
        # http://goo.gl/sWGbH
        return usage_ntuple(total, used, free, round(percent, 1))
    
    
    if __name__ == '__main__':
        for part in disk_partitions():
            print part
            print "    %s\n" % str(disk_usage(part.mountpoint))
    

    上面的代码打印在我的盒子上:

    giampaolo@ubuntu:~/dev$ python foo.py 
    partition(device='/dev/sda3', mountpoint='/', fstype='ext4')
        usage(total=21378641920, used=4886749184, free=15405903872, percent=22.9)
    
    partition(device='/dev/sda7', mountpoint='/home', fstype='ext4')
        usage(total=30227386368, used=12137168896, free=16554737664, percent=40.2)
    
    partition(device='/dev/sdb1', mountpoint='/media/1CA0-065B', fstype='vfat')
        usage(total=7952400384, used=32768, free=7952367616, percent=0.0)
    
    partition(device='/dev/sr0', mountpoint='/media/WB2PFRE_IT', fstype='iso9660')
        usage(total=695730176, used=695730176, free=0, percent=100.0)
    
    partition(device='/dev/sda6', mountpoint='/media/Dati', fstype='fuseblk')
        usage(total=914217758720, used=614345637888, free=299872120832, percent=67.2)
    

    【讨论】:

    【解决方案6】:

    这并没有给出分区的名称,但您可以使用statvfs Unix 系统调用直接获取文件系统统计信息。要从 Python 调用它,请使用 os.statvfs('/home/foo/bar/baz')。

    结果中的相关字段,according to POSIX:

    unsigned long f_frsize   Fundamental file system block size. 
    fsblkcnt_t    f_blocks   Total number of blocks on file system in units of f_frsize. 
    fsblkcnt_t    f_bfree    Total number of free blocks. 
    fsblkcnt_t    f_bavail   Number of free blocks available to 
                             non-privileged process.
    

    为了理解这些值,乘以f_frsize:

    import os
    statvfs = os.statvfs('/home/foo/bar/baz')
    
    statvfs.f_frsize * statvfs.f_blocks     # Size of filesystem in bytes
    statvfs.f_frsize * statvfs.f_bfree      # Actual number of free bytes
    statvfs.f_frsize * statvfs.f_bavail     # Number of free bytes that ordinary users
                                            # are allowed to use (excl. reserved space)
    

    【讨论】:

    • 我刚刚在带有 ubifs 的嵌入式系统上遇到了这个问题。它产生了 100MB 的免费空间,其中只有 10 个可用。我不确定 100 是从哪里来的。
    【解决方案7】:

    找出它的最简单方法。

    import os
    from collections import namedtuple
    
    DiskUsage = namedtuple('DiskUsage', 'total used free')
    
    def disk_usage(path):
        """Return disk usage statistics about the given path.
    
        Will return the namedtuple with attributes: 'total', 'used' and 'free',
        which are the amount of total, used and free space, in bytes.
        """
        st = os.statvfs(path)
        free = st.f_bavail * st.f_frsize
        total = st.f_blocks * st.f_frsize
        used = (st.f_blocks - st.f_bfree) * st.f_frsize
        return DiskUsage(total, used, free)
    

    【讨论】:

    • 已使用 = 全部 - 免费?
    【解决方案8】:

    从 Python 3.3 开始,使用标准库有一种简单直接的方法:

    $ cat free_space.py 
    #!/usr/bin/env python3
    
    import shutil
    
    total, used, free = shutil.disk_usage(__file__)
    print(total, used, free)
    
    $ ./free_space.py 
    1007870246912 460794834944 495854989312
    

    这些数字以字节为单位。请参阅the documentation 了解更多信息。

    【讨论】:

      【解决方案9】:
      import os
      
      def disk_stat(path):
          disk = os.statvfs(path)
          percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
          return percent
      
      
      print disk_stat('/')
      print disk_stat('/data')
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
      • disk_stat 方法不接受任何参数。但是,使用os.statvfs 的想法很好。
      【解决方案10】:

      对于问题的第二部分,“获取给定分区的使用情况统计信息”,psutil 使用disk_usage(path) 函数使这变得容易。给定路径,disk_usage() 返回一个命名元组,包括以字节表示的总空间、已用空间和可用空间,以及使用百分比。

      文档中的简单示例:

      >>> import psutil
      >>> psutil.disk_usage('/')
      sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
      

      Psutil 适用于从 2.6 到 3.6 的 Python 版本以及 Linux、Windows 和 OSX 以及其他平台。

      【讨论】:

        【解决方案11】:

        检查您的 Windows PC 上的磁盘使用情况如下:

        import psutil
        
        fan = psutil.disk_usage(path="C:/")
        print("Available: ", fan.total/1000000000)
        print("Used: ", fan.used/1000000000)
        print("Free: ", fan.free/1000000000)
        print("Percentage Used: ", fan.percent, "%")
        

        【讨论】:

          【解决方案12】:

          11 年后,但扩展了其他答案。

          import psutil
          
          #File systems
          value=psutil.disk_partitions()
          
          for i in value:
              va=i[1]
              value2=psutil.disk_usage(va).percent
              print(value2)
              fs_space[va]=value2
          

          这是将它添加到字典中,只抓取我需要的百分比,但您可以抓取所有值或从总数、已使用、免费或百分比中选择您想要的值。

          Official documentation helped a lot

          【讨论】:

            猜你喜欢
            • 2011-09-03
            • 1970-01-01
            • 2015-04-06
            • 2019-06-26
            • 2010-12-15
            • 2016-09-18
            • 1970-01-01
            • 2020-09-12
            • 1970-01-01
            相关资源
            最近更新 更多