使用python的卷上剩余的跨平台空间 [英] Cross-platform space remaining on volume using 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()
和 GetDiskFreeSpaceEx
.
Also see the documentation for os.statvfs()
and GetDiskFreeSpaceEx
.
这篇关于使用python的卷上剩余的跨平台空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!