python - 在 Python 中获取硬盘大小

标签 python macos python-2.7 hard-drive

我正在尝试使用 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 中已弃用,您知道任何替代方案吗?

最佳答案

适用于 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

关于python - 在 Python 中获取硬盘大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48929553/

相关文章:

python 字典。 if 语句

python - 如何从图像中裁剪边界框

python - 如何将所有属性导入 numpy 模块?

macos - 如何在 MacOS 10.13.3 (High Sierra) 上安装 GDB

python - 我可以使用 groupby 在 python 中解决这个问题吗?

python - 代码不适用于用户输入 A 或 B 并交换到所有 A

macos - 在 YUV 中绘制 CGImageRef

macos - VBA 在 Windows Excel 上运行,但不能在 Mac Excel 中运行

Django celery : Import error - no module named task

python - 操作系统错误 : socket no longer exists (Python IDLE error)