使用python在卷上剩余的跨平台空间 [英] Cross-platform space remaining on volume using python

查看:25
本文介绍了使用python在卷上剩余的跨平台空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种在 linux、Windows 和 OS X 上使用 python 确定磁盘卷上剩余空间的方法.我目前正在解析各种系统调用(df、dir)的输出来实现这一点 - 有没有更好的方法?

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() 的文件.

Note that you must pass a directory name for GetDiskFreeSpaceEx() to work (statvfs() works on both files and directories). You can get a directory name from a file with os.path.dirname().

另请参阅os.statvfs()<的文档/code>GetDiskFreeSpaceEx.

Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx.

这篇关于使用python在卷上剩余的跨平台空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆