我正在尝试使用 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/