在Python中获取硬盘大小 [英] Get hard disk size in Python

查看:1143
本文介绍了在Python中获取硬盘大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get the hard drive size and free space using Python (I am using Python 2.7 with macOS).

我正在尝试使用os.statvfs('/'),尤其是以下代码. 我在做什么正确吗?我应该使用变量giga的哪个定义?

I am trying with os.statvfs('/'), especially with the following code. Is it correct what I am doing? Which definition of the variable giga shall I use?

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中已弃用,您知道其他选择吗?

statvfs is deprecated in Python 3, do you know any alternative?

推荐答案

适用于Python 2直至Python 3.3


通知:正如评论部分中提到的一些人所述,此解决方案适用于 Python 3.3 及更高版本.对于 Python 2.7 ,最好使用 psutil 库,该库具有 disk_usage 函数,其中包含有关总计已使用免费磁盘空间:

For Python 2 till Python 3.3


Notice: As a few people mentioned in the comment section, this solution will work for Python 3.3 and above. For Python 2.7 it is best to use the psutil library, which has a disk_usage function, containing information about total, used and free disk space:

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 函数,返回一个命名元组以及硬盘驱动器中的总空间,已用空间和可用空间.


Python 3.3 and above:

For Python 3.3 and above, you can use the shutil module, which has a disk_usage function, returning a named tuple with the amounts of total, used and free space in your hard drive.

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

You can call the function as below and get all information about your disk's space:

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中获取硬盘大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆