繁体   English   中英

使用 python 的卷上剩余的跨平台空间

[英]Cross-platform space remaining on volume using python

I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?

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的文档。

安装psutil使用pip install psutil 然后您可以使用以下方法获取可用空间量(以字节为单位):

import psutil
print(psutil.disk_usage(".").free)

您可以将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)

如果您正在运行 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 为单位的总空间、已用空间和可用空间。

如果您不想添加另一个依赖项,您可以为 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'

从 Python 3.3 开始,您可以使用shutil.disk_usage("/").free从 Windows 和 UNIX 的标准库:)

一个很好的跨平台方式是使用 psutil: http ://pythonhosted.org/psutil/#disks(请注意,您需要 psutil 0.3.0 或更高版本)。

您可以使用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 上返回正确的值

import win32file    

def get_free_space(dirname):
    secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
    return secsPerClus * bytesPerSec * nFreeClus

os.statvfs()函数是为类 Unix 平台(包括 OS X)获取该信息的更好方法。 Python 文档说“可用性:Unix”,但值得检查它是否也适用于您的 Python 构建中的 Windows(即文档可能不是最新的)。

否则,您可以使用pywin32库直接调用GetDiskFreeSpaceEx函数。

我不知道有什么跨平台的方法可以实现这一点,但也许对您来说一个很好的解决方法是编写一个包装类来检查操作系统并为每个类使用最佳方法。

对于 Windows,win32 扩展中有GetDiskFreeSpaceEx方法。

以前的大多数答案都是正确的,我使用的是 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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM