简体   繁体   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? 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

Note that you must pass a directory name for GetDiskFreeSpaceEx() to work ( statvfs() works on both files and directories).请注意,您必须GetDiskFreeSpaceEx()传递一个目录名才能工作( statvfs()对文件和目录都有效)。 You can get a directory name from a file with os.path.dirname() .您可以使用os.path.dirname()从文件中获取目录名称。

Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx .另请参阅os.statvfs()GetDiskFreeSpaceEx的文档。

Install psutil using pip install psutil .安装psutil使用pip install psutil Then you can get the amount of free space in bytes using:然后您可以使用以下方法获取可用空间量(以字节为单位):

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

You could use the wmi module for windows and os.statvfs for unix您可以将wmi模块用于 windows,将 os.statvfs 用于 unix

for window用于窗户

import wmi

c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
    print( d.Caption, d.FreeSpace, d.Size, d.DriveType)

for unix or linux适用于 unix 或 linux

from os import statvfs

statvfs(path)

If you're running python3:如果您正在运行 python3:

Using shutil.disk_usage() with os.path.realpath('/') name-regularization works: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('/'))])

Or或者

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)

giving you the total, used, & free space in MB.为您提供以 MB 为单位的总空间、已用空间和可用空间。

If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly.如果您不想添加另一个依赖项,您可以为 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 或更高版本)。

You can use df as a cross-platform way.您可以使用df作为跨平台方式。 It is a part of GNU core utilities .它是GNU 核心实用程序的一部分。 These are the core utilities which are expected to exist on every operating system.这些是预期存在于每个操作系统上的核心实用程序。 However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy).但是,默认情况下它们不会安装在 Windows 上(在这里, GetGnuWin32派上用场)。

df is a command-line utility, therefore a wrapper required for scripting purposes. df是一个命令行实用程序,因此需要一个用于编写脚本的包装器。 For example:例如:

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

Below code returns correct value on windows下面的代码在 Windows 上返回正确的值

import win32file    

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

The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). os.statvfs()函数是为类 Unix 平台(包括 OS X)获取该信息的更好方法。 The Python documentation says "Availability: Unix" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date). Python 文档说“可用性:Unix”,但值得检查它是否也适用于您的 Python 构建中的 Windows(即文档可能不是最新的)。

Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function.否则,您可以使用pywin32库直接调用GetDiskFreeSpaceEx函数。

I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.我不知道有什么跨平台的方法可以实现这一点,但也许对您来说一个很好的解决方法是编写一个包装类来检查操作系统并为每个类使用最佳方法。

For Windows, there's the GetDiskFreeSpaceEx method in the win32 extensions.对于 Windows,win32 扩展中有GetDiskFreeSpaceEx方法。

Most previous answers are correct, I'm using Python 3.10 and shutil.以前的大多数答案都是正确的,我使用的是 Python 3.10 和shutil。 My use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the documentation )我的用例是 Windows 和 C 驱动器(但你应该能够为你扩展这个 Linux 和 Mac 以及(这里是文档

Here is the example for Windows:这是 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