数据框百分比使用之谜
我对Unix的df
命令是怎么计算文件系统使用百分比的有点困惑。我写了一个小脚本来运行df
,想独立算出同样的信息:
$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.0 (Santiago)
$ cat dftest.py
#! /usr/bin/python
import sys
import os
import subprocess
def reportUsage(label, total, free):
used = total - free
print "%s=%dK, used=%dK (%d%%)" % (label, free, used, used*100/total)
p = subprocess.Popen(["df", "-k", "."], stdout=subprocess.PIPE)
print p.stdout.read()
rc = p.wait()
stat = os.statvfs(".")
total = (stat.f_bsize * stat.f_blocks) / 1024
free = (stat.f_bsize * stat.f_bfree) / 1024
avail = (stat.f_bsize * stat.f_bavail) / 1024
print "Total=%dK" % total
reportUsage("Free", total, free)
reportUsage("Avail", total, avail)
$ ./dftest.py
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda4 20158332 3930688 15203644 21% /home
Total=20158332K
Free=16227644K, used=3930688K (19%)
Avail=15203644K, used=4954688K (24%)
$
所以,总字节数、可用空间(普通用户可用的)和已用空间(根据空闲空间计算)都一致,太好了!那么为什么df
显示的是21%的使用率呢?我觉得应该是19%,因为那就是实际使用的量。我漏掉了什么吗?这可不是简单的四舍五入错误吧?
3 个回答
0
total
、free
和avail
这些值都是通过整数运算来计算的,而不是小数运算。你可以试试
total = (stat.f_bsize * stat.f_blocks) / 1024.0
这样可以强制进行小数运算。对比一下
>>> 9 / 2
4
>>> 9 / 2.0
4.5
(这个问题只出现在Python 2中,如果没有使用from __future__ import division
的话。)
1
补充一下zhujs
的评论,造成这个差异的原因是文件系统创建时分配的保留空间。你可以运行以下命令来查看保留空间和你的文件系统块大小。
$ sudo tune2fs -l /dev/sda4 | grep -iE 'reserved block count|block size'
这取决于你的文件系统,但我猜你的系统输出可能是这样的:
Reserved block count: 256000
Block size: 4096
这表示有1024000个1K的块被保留了。df
命令在已用空间下报告这个,因为保留空间对普通用户来说是不可用的。
2
我觉得这是因为在你的情况下,你的文件系统占用了1024000个块(20158332-3930688-15203644),所以df
命令报告的使用百分比是(1024000+3930688) / 20158332 = 24%。而在你的Python代码中,你只是计算了使用百分比为3930688 / 20158332 = 19%。