Naposledy aktivní 10 months ago

這段程式碼透過 DiskUsage 類別來檢查指定路徑的磁碟空間使用情況,包括總空間、已使用空間、可用空間及使用率,並提供 format_size 方法將數值轉換成人類可讀的格式(如 KB、MB、GB)。適用於系統監控、伺服器管理或儲存資源分析。

Revize d6f7cabaa64010446393926119985214e4672e66

disk_usage_checker.py Raw
1import os
2import shutil
3
4class DiskUsage:
5 def __init__(self, path="/"):
6 """
7 初始化 DiskUsage 類別,指定檢查的路徑(預設為根目錄 /)。
8
9 :param path: 要檢查的檔案系統路徑。
10 """
11 self.path = path
12
13 def get_usage(self):
14 """
15 取得指定路徑的硬碟空間使用情況。
16
17 :return: 包含總空間、使用空間、剩餘空間和使用率的字典。
18 """
19 try:
20 total, used, free = shutil.disk_usage(self.path)
21 usage_percent = (used / total) * 100 if total > 0 else 0
22 return {
23 "path": self.path,
24 "total_space": total, # 總空間(以位元組為單位)
25 "used_space": used, # 已使用空間(以位元組為單位)
26 "free_space": free, # 可用空間(以位元組為單位)
27 "usage_percent": usage_percent # 使用率(百分比)
28 }
29 except Exception as e:
30 raise RuntimeError(f"Error getting disk usage for path '{self.path}': {e}")
31
32 @staticmethod
33 def format_size(size_in_bytes):
34 """
35 將位元組大小格式化為人類可讀的格式(如 KB、MB、GB)。
36
37 :param size_in_bytes: 位元組大小。
38 :return: 格式化的大小字串。
39 """
40 for unit in ["B", "KB", "MB", "GB", "TB"]:
41 if size_in_bytes < 1024:
42 return f"{size_in_bytes:.2f} {unit}"
43 size_in_bytes /= 1024
44 return f"{size_in_bytes:.2f} PB" # 假設不會超過 PB 級別
45
46# 測試範例
47if __name__ == "__main__":
48 # 初始化類別,檢查根目錄空間
49 disk = DiskUsage("/")
50
51 # 獲取硬碟空間使用情況
52 usage = disk.get_usage()
53
54 # 輸出結果
55 print("Disk Usage for Path:", usage["path"])
56 print("Total Space:", disk.format_size(usage["total_space"]))
57 print("Used Space:", disk.format_size(usage["used_space"]))
58 print("Free Space:", disk.format_size(usage["free_space"]))
59 print(f"Usage Percentage: {usage['usage_percent']:.2f}%")
60