python どらいぶ使用状況 | 60歳を迎えて、思うこと。

60歳を迎えて、思うこと。

いつの間にか、「60」という年月が経ちました。
残り少ないか多いか?わかりませんが。
じじぃ~の「ひとりごと」を細々と続けられれば。。。

python どらいぶ使用状況

ねこねこ
いぬいぬ

ドライブの
使用量を 簡単に 把握したい!

というわけで・・・

【chatGPT】様にお願い

# ====
# 【chatGPT】
# これは**自分用のユーティリティ**として結構使えると思います。
# 以下のスクリプトなら、
# * `psutil` を使用
# * 日時付きヘッダー
# * `YYYYMMDD.txt` で保存
# * 画面にも表示
# * 使用率80%以上で `!!`
# * 使用率90%以上で `***FULL***`
# * 列を揃えて見やすく表示
# となっています。


import psutil
from datetime import datetime
import os

# =====================================
# ドライブ情報取得
# =====================================
# ★絶対死守★ スクリプトのディレクトリをカレントディレクトリに変更
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
print(f"Current directory: {os.getcwd()}")

now = datetime.now()

filename = now.strftime("%Y%m%d") + ".txt"

lines = []

lines.append("Drive Information")
lines.append(now.strftime("%Y-%m-%d %H:%M:%S"))
lines.append("")
lines.append(
    f"{'Drive':<6}"
    f"{'Total':>10}"
    f"{'Used':>10}"
    f"{'Free':>10}"
    f"{'Use%':>8}   Status"
)
lines.append("-" * 58)

for part in psutil.disk_partitions():

    try:
        usage = psutil.disk_usage(part.mountpoint)
    except PermissionError:
        continue

    total = usage.total / (1024**3)
    used  = usage.used  / (1024**3)
    free  = usage.free  / (1024**3)
    percent = usage.percent

    # 警告表示
    status = ""
    if percent >= 90:
        status = "***FULL***"
    elif percent >= 80:
        status = "!!"

    line = (
        f"{part.device:<6}"
        f"{total:>10.1f}G"
        f"{used:>10.1f}G"
        f"{free:>10.1f}G"
        f"{percent:>7.1f}%   "
        f"{status}"
    )

    lines.append(line)

# ==========================
# 画面表示
# ==========================

for line in lines:
    print(line)

# ==========================
# ファイル保存
# ==========================

with open(filename, "w", encoding="utf-8") as f:
    f.write("\n".join(lines))

print()
print(f"保存しました : {filename}")

# # ==============================

よわ まんぞく で ありんず

じじぃ~