我需要一种使用Python在Linux、Windows和OS X上确定磁盘卷剩余空间的方法。目前,我正在解析各个系统调用(如df、dir)的输出来完成此操作 - 是否有更好的方法?
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
请注意,您必须传递目录名称才能使 GetDiskFreeSpaceEx()
函数工作(statvfs()
函数可用于文件和目录)。您可以使用 os.path.dirname()
从文件中获取目录名称。os.statvfs()
和 GetDiskFreeSpaceEx
的文档。.f_bfree
是文件系统中空闲块的总数。需要乘以.f_bsize
以获取字节数。 - jfs.f_bsize
得到的值要大得多,因为f_bsize
是首选块大小,而.f_frsize
是基本块大小并给出正确的值。在我的Linux测试系统上,两个值都是相同的,因此.f_frsize
应该始终可用。 - Dennis Bliefernichtos.name == 'nt'
! - ewerybody使用pip install psutil
安装psutil。然后,您可以使用以下代码获取可用空间的字节数:
import psutil
print(psutil.disk_usage(".").free)
psutil
的陈旧链接。由于 disk_usage.free
通常返回一个巨大的64位整数,我建议您还要向人们展示 disk_usage.percent
。对我来说,psutil.disk_usage(".").percent < 99.9
更清晰... - smciimport wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
适用于Unix或Linux操作系统
from os import statvfs
statvfs(path)
psutil
处理它? - Fr0zenFyrctypes
是内置的! - ewerybody使用shutil.disk_usage()
和os.path.realpath('/')
名称规范化一起工作:
from os import path
from shutil import disk_usage
print([i / 1000000 for i in disk_usage(path.realpath('/'))])
或者
total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\Users\\phannypack'))
print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)
提供给您以MB为单位的总空间、已用空间和可用空间。
ctypes
,这可能需要查阅 MSDN 文档并确保类型被正确强制转换,这很麻烦。 - pstatix如果您不想添加其他依赖项,您可以在Windows上使用ctypes直接调用win32函数调用。
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
from subprocess import PIPE, Popen
def free_volume(filename):
"""Find amount of disk space available to the current user (in bytes)
on the file system containing filename."""
stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
return int(stats.splitlines()[1].split()[3]) * 1024
import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
os.statvfs() 函数是获取 Unix-like 平台(包括 OS X)上该信息的更好方法。Python 文档说“可用性:Unix”,但值得检查它是否也适用于你所构建的 Python 的 Windows 版本(即,文档可能已经不是最新的)。
否则,您可以使用 pywin32 库直接调用 GetDiskFreeSpaceEx 函数。