[英]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)
將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.