在Python中获取硬盘大小

70

我试图使用Python(我正在使用macOS和Python 2.7)获取硬盘驱动器大小和可用空间。

我尝试使用 os.statvfs('/'),特别是下面的代码。 我现在的做法正确吗?我应该使用哪个变量定义来表示“giga”?

import os

def get_machine_storage():
    result=os.statvfs('/')
    block_size=result.f_frsize
    total_blocks=result.f_blocks
    free_blocks=result.f_bfree
    # giga=1024*1024*1024
    giga=1000*1000*1000
    total_size=total_blocks*block_size/giga
    free_size=free_blocks*block_size/giga
    print('total_size = %s' % total_size)
    print('free_size = %s' % free_size)

get_machine_storage()

编辑: statvfs在Python 3中已被弃用,您知道有什么替代品吗?


2
你可以在这里查看如何解释输出。 - Vasilis G.
@VasilisG。谢谢。我看到这个方法在Python 3中已经被弃用了,有替代方案吗? - Nisba
3
尝试使用shutil模块中的disk_usage - Vasilis G.
可能对您有用的另一个问题:https://dev59.com/V2855IYBdhLWcg3wlFaP - David Stevens
6个回答

155

适用于Python 2至Python 3.3


注意:正如评论部分中有几个人提到的,此解决方案适用于Python 3.3及以上版本。对于Python 2.7,最好使用psutil库,该库具有一个disk_usage函数,其中包含有关磁盘空间的已用可用信息。
import psutil

hdd = psutil.disk_usage('/')

print ("Total: %d GiB" % hdd.total / (2**30))
print ("Used: %d GiB" % hdd.used / (2**30))
print ("Free: %d GiB" % hdd.free / (2**30))

Python 3.3 及以上版本:

对于 Python 3.3 及以上版本,您可以使用 shutil 模块,该模块具有一个 disk_usage 函数,返回一个命名元组,其中包含硬盘驱动器中总空间、已使用空间和可用空间的数量。

您可以按照以下方式调用该函数并获取有关硬盘空间的所有信息:

import shutil

total, used, free = shutil.disk_usage("/")

print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))

输出:

Total: 931 GiB
Used: 29 GiB
Free: 902 GiB

4
不错的回答,但只计算千兆字节大小,而totalusedfree的大小可以是任何值。如果你想的话,你甚至可以使用hurry.filesize,它会自动处理这个问题 :) - Wondercricket
2
@Wondercricket确实,每次需要不同的单位时,您都必须修改除数。感谢您的建议 :) - Vasilis G.
9
仅自Python 3.3版本以后。 - themadmax
3
这将为您提供分区的大小,而不是整个磁盘的大小。 - Aran-Fey
虽然这个解决方案可能对某些情况有效,但在 Python 3.3 版本以下的环境中无法使用。 - Xonshiz
我有一张32GB的SD卡,文件系统被删除了,显示只有8GB可用。 - jaromrax

19

https://pypi.python.org/pypi/psutil

import psutil

obj_Disk = psutil.disk_usage('/')

print (obj_Disk.total / (1024.0 ** 3))
print (obj_Disk.used / (1024.0 ** 3))
print (obj_Disk.free / (1024.0 ** 3))
print (obj_Disk.percent)

3
让我建议使用 float(1<<30) 而不是 (1024.0 ** 3) - Chen Levy

8

这段代码是正确的,但你使用了错误的字段,在不同的系统上可能会得到错误的结果。正确的方法应该是:

>>> os.system('df -k /')
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/root       14846608 3247272  10945876  23% /

>>> disk = os.statvfs('/')
>>> (disk.f_bavail * disk.f_frsize) / 1024
10945876L

不适用于Windows。 - undefined
@lmocsi OP 问的是关于 macOS 的问题 - undefined
被接受的解决方案可以独立于操作系统运行。 - undefined
@lmocsi 接受的答案与 os.system('df -k /') 相比给出了错误的结果。 - undefined

3

当你不知道如何处理函数的结果时,打印出类型可以有所帮助。

print type(os.statvfs('/')) 返回 <type 'posix.statvfs_result'>

这意味着它不是像字符串或整数那样的内置类实例。

您可以使用 dir(instance) 检查该实例可以执行什么操作。

print dir(os.statvfs('/')) 打印所有属性、函数、变量等。

['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'f_bavail', 'f_bfree', 'f_blocks',
'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize',
'f_namemax', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields']

通过访问其中一个变量,例如os.statvfs('/').f_ffree,您可以提取一个整数。
使用print type(os.statvfs('/').f_ffree)进行双重检查, 它会打印出<type 'int'>

1
f_ffree 是指空闲文件描述符的数量,与磁盘上的可用空间无关。 - lenik
@lenik 不是的,我是从 https://iterm2.com/python-api/examples/diskspace.html 获取的,我没有看到你已经写了一个真正的答案,抱歉。 - Pylinux

0
一个单行解决方案,基于这里的答案显示以GiB为单位的磁盘大小:
>>> import shutil

>>> [f"{y}: {x//(2**30)} GiB" for x, y in zip(shutil.disk_usage('/'), shutil.disk_usage('/')._fields)]
['total: 228 GiB', 'used: 14 GiB', 'free: 35 GiB']

0

这个帖子中所有的答案都只提供了根分区的磁盘大小。以下是我的代码,适用于需要完整硬盘大小的人:

total = int()
used  = int()
free  = int()

for disk in psutil.disk_partitions():
    if disk.fstype:
        total += int(psutil.disk_usage(disk.mountpoint).total)
        used  += int(psutil.disk_usage(disk.mountpoint).used)
        free  += int(psutil.disk_usage(disk.mountpoint).free)

print(f'''    
    TOTAL DISK SPACE : {round(total / (1024.0 ** 3), 4)} GiB
    USED DISK SPACE  : {round(used / (1024.0 ** 3), 4)} GiB
    FREE DISK SPACE  : {round(free / (1024.0 ** 3), 4)} GiB
''')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接