提问人: 提问时间:9/9/2008 更新时间:7/26/2022 访问量:48552
使用 python 的卷上剩余的跨平台空间
Cross-platform space remaining on volume using python
问:
我需要一种方法来确定磁盘卷上的剩余空间 在 linux、Windows 和 OS X 上使用 python。我目前正在解析各种系统调用(df、dir)的输出来实现这一目标 - 有没有更好的方法?
答:
os.statvfs() 函数是获取类 Unix 平台(包括 OS X)信息的更好方法。Python 文档说“可用性:Unix”,但值得检查它是否也能在 Windows 上运行在您的 Python 版本中(即文档可能不是最新的)。
否则,可以使用 pywin32 库直接调用 GetDiskFreeSpaceEx 函数。
评论
我不知道有任何跨平台方法可以实现这一点,但也许对你来说一个很好的解决方法是编写一个包装类来检查操作系统并为每个操作系统使用最佳方法。
对于 Windows,win32 扩展中有 GetDiskFreeSpaceEx 方法。
您可以将 df 用作跨平台方式。它是 GNU 核心实用程序的一部分。这些是预计存在于每个操作系统上的核心实用程序。但是,默认情况下,它们不会安装在 Windows 上(在这里,GetGnuWin32 派上用场)。
df 是一个命令行实用程序,因此是编写脚本所需的包装器。 例如:
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
评论
如果您不想添加其他依赖项,可以在 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'
评论
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
.f_bsize
f_bsize
.f_frsize
.f_frsize
一个好的跨平台方法是使用 psutil: http://pythonhosted.org/psutil/#disks(请注意,您需要 psutil 0.3.0 或更高版本)。
评论
您可以将 wmi 模块用于 windows,将 os.statvfs 用于 unix
用于窗口
import 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
ctypes
使用 安装 psutil。然后,您可以使用以下命令获取可用空间量(以字节为单位):pip install psutil
import psutil
print(psutil.disk_usage(".").free)
评论
psutil
disk_usage.free
disk_usage.percent
psutil.disk_usage(".").percent < 99.9
以下代码在 Windows 上返回正确的值
import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
从 Python 3.3 开始,您可以使用 Windows 和 UNIX 标准库中的 shutil.disk_usage(“/”).free:)
如果您运行的是 python3:
与名称正则化一起使用可以工作: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
以前的大多数答案都是正确的,我使用的是 Python 3.10 和 shutil。 我的用例是 Windows 和 C 驱动器(但您也应该能够为 Linux 和 Mac 扩展它(这是文档)
下面是 Windows 的示例:
import shutil
total, used, free = shutil.disk_usage("C:/")
print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))
评论