我正在寻找我的 HD 上的可用字节数,但在 python 上这样做有困难。
我尝试了以下方法:
import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
但是,在 OS/X 上,它给了我 17529020874752 字节,大约是 1.6 TB,这非常好,但不幸的是,这不是真的。
得到这个数字的最佳方法是什么?
尝试使用f_frsize
而不是f_bsize
.
>>> s = os.statvfs('/')
>>> (s.f_bavail * s.f_frsize) / 1024
23836592L
>>> os.system('df -k /')
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/disk0s2 116884912 92792320 23836592 80% /
在 UNIX 上:
import os
from collections import namedtuple
_ntuple_diskusage = namedtuple('usage', 'total used free')
def disk_usage(path):
"""Return disk usage statistics about the given path.
Returned valus is a named tuple with attributes 'total', 'used' and
'free', which are the amount of total, used and free space, in bytes.
"""
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return _ntuple_diskusage(total, used, free)
用法:
>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>
对于 Windows,您可以使用psutil。
在 python 3.3 及更高版本中,shutil 为您提供相同的功能
>>> import shutil
>>> shutil.disk_usage("/")
usage(total=488008343552, used=202575314944, free=260620050432)
>>>
也可以使用Psutil 模块。
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
文档可以在这里找到。
def FreeSpace(drive):
""" Return the FreeSape of a shared drive in bytes"""
try:
fso = com.Dispatch("Scripting.FileSystemObject")
drv = fso.GetDrive(drive)
return drv.FreeSpace
except:
return 0
它不是独立于操作系统的,但这适用于 Linux,也可能适用于 OS X:
打印 commands.getoutput('df .').split('\n')[1].split()[3]
它是如何工作的?它得到“df”的输出。命令,它为您提供有关当前目录所属分区的磁盘信息,将其分成两行(就像它打印到屏幕上一样),然后取第二行(通过在后面附加 [1]首先 split()),然后将该行拆分为不同的以空格分隔的部分,最后为您提供该列表中的第 4 个元素。
>>> commands.getoutput('df .')
'Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/sda3 80416836 61324872 15039168 81% /'
>>> commands.getoutput('df .').split('\n')
['Filesystem 1K-blocks Used Available Use% Mounted on', '/dev/sda3 80416836 61324908 15039132 81% /']
>>> commands.getoutput('df .').split('\n')[1]
'/dev/sda3 80416836 61324908 15039132 81% /'
>>> commands.getoutput('df .').split('\n')[1].split()
['/dev/sda3', '80416836', '61324912', '15039128', '81%', '/']
>>> commands.getoutput('df .').split('\n')[1].split()[3]
'15039128'
>>> print commands.getoutput('df .').split('\n')[1].split()[3]
15039128
有什么问题
import subprocess
proc= subprocess.Popen( "df", stdout=subprocess.PIPE )
proc.stdout.read()
proc.wait()