Nis*_*sba 17 python 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()
Run Code Online (Sandbox Code Playgroud)
编辑:
statvfs在Python 3中已弃用,您知道其他选择吗?
Vas*_* G. 33
我在我的机器上运行它(Python 3.4):
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)))
Run Code Online (Sandbox Code Playgroud)
输出:
Total: 931 GiB
Used: 29 GiB
Free: 902 GiB
Run Code Online (Sandbox Code Playgroud)
编辑:适用于Python 3.6.
Fau*_*nco 13
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)
Run Code Online (Sandbox Code Playgroud)
代码大致正确,但是您使用了错误的字段,这可能会在不同的系统上给您错误的结果。正确的方法是:
>>> 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
Run Code Online (Sandbox Code Playgroud)