import os import shutil class DiskUsage: def __init__(self, path="/"): """ 初始化 DiskUsage 類別,指定檢查的路徑(預設為根目錄 /)。 :param path: 要檢查的檔案系統路徑。 """ self.path = path def get_usage(self): """ 取得指定路徑的硬碟空間使用情況。 :return: 包含總空間、使用空間、剩餘空間和使用率的字典。 """ try: total, used, free = shutil.disk_usage(self.path) usage_percent = (used / total) * 100 if total > 0 else 0 return { "path": self.path, "total_space": total, # 總空間(以位元組為單位) "used_space": used, # 已使用空間(以位元組為單位) "free_space": free, # 可用空間(以位元組為單位) "usage_percent": usage_percent # 使用率(百分比) } except Exception as e: raise RuntimeError(f"Error getting disk usage for path '{self.path}': {e}") @staticmethod def format_size(size_in_bytes): """ 將位元組大小格式化為人類可讀的格式(如 KB、MB、GB)。 :param size_in_bytes: 位元組大小。 :return: 格式化的大小字串。 """ for unit in ["B", "KB", "MB", "GB", "TB"]: if size_in_bytes < 1024: return f"{size_in_bytes:.2f} {unit}" size_in_bytes /= 1024 return f"{size_in_bytes:.2f} PB" # 假設不會超過 PB 級別 # 測試範例 if __name__ == "__main__": # 初始化類別,檢查根目錄空間 disk = DiskUsage("/") # 獲取硬碟空間使用情況 usage = disk.get_usage() # 輸出結果 print("Disk Usage for Path:", usage["path"]) print("Total Space:", disk.format_size(usage["total_space"])) print("Used Space:", disk.format_size(usage["used_space"])) print("Free Space:", disk.format_size(usage["free_space"])) print(f"Usage Percentage: {usage['usage_percent']:.2f}%")