disk_usage_checker.py
· 2.1 KiB · Python
原始文件
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}%")
| 1 | import os |
| 2 | import shutil |
| 3 | |
| 4 | class 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 | # 測試範例 |
| 47 | if __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 |