查找包含给定文件的文件系统的大小和可用空间

2025-04-17 09:02:00
admin
原创
15
摘要:问题描述:我在 Linux 上使用 Python 2.6。最快的方法是什么?确定哪个分区包含给定的目录或文件?例如,假设/dev/sda2安装在 上/home,并且/dev/mapper/foo安装在 上/home/foo。我想从字符串中"/home/foo/bar/baz"恢复对(&qu...

问题描述:

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

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

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

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


解决方案 1:

这不会提供分区的名称,但您可以使用statvfsUnix 系统调用直接获取文件系统统计信息。要从 Python 中调用它,请使用os.statvfs('/home/foo/bar/baz')

根据 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)

解决方案 2:

从 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

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

解决方案 3:

如果您只是需要设备上的可用空间,请参阅下面的答案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 = \n    output.split("
")[1].split()

请注意,这相当脆弱,因为它取决于df输出的具体格式,但我不知道还有更健壮的解决方案。(下面有几个依赖于/proc文件系统的解决方案,它们的可移植性甚至比这个更差。)

解决方案 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('
').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

聚苯乙烯

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

解决方案 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
" % 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:

找出它的最简单方法。

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)

解决方案 7:

对于问题的第二部分“获取给定分区的使用情况统计信息”,psutil 的disk_usage(path)函数可以简化这一操作。给定一个路径,disk_usage()返回一个命名元组,其中包含以字节为单位的总空间、已用空间和可用空间,以及使用率百分比。

文档中的简单示例:

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

Psutil 适用于 Python 2.6 至 3.6 版本以及 Linux、Windows 和 OSX 等平台。

解决方案 8:

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

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

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

解决方案 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')

解决方案 10:

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

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

官方文档很有帮助

解决方案 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:

在 Linux 中,目录通常/proc包含此类信息,它是一个虚拟文件系统。例如,/proc/mounts提供有关当前已挂载磁盘的信息;您可以直接解析它。像 这样的实用程序topdf使用/proc

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

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用