Monitor Disk Usage and Alert in Python

A Python script that checks disk usage percentage against a threshold and returns an ALERT or OK message with free space details.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

17 lines
Python 3.9+
import shutil
import os

def check_disk_usage(path="/", threshold=85.0):
    usage = shutil.disk_usage(path)
    percent_used = (usage.used / usage.total) * 100
    
    if percent_used > threshold:
        return (f"ALERT: Disk usage at {percent_used:.1f}% on {path} "
                f"(exceeds {threshold}% threshold). "
                f"{usage.free / (1024**3):.2f} GB free")
    return (f"OK: Disk usage at {percent_used:.1f}% on {path} "
            f"({usage.free / (1024**3):.2f} GB free)")

if __name__ == "__main__":
    print(check_disk_usage("/", 90))
    print(check_disk_usage("/tmp", 95))

Output

stdout
ALERT: Disk usage at 92.5% on / (exceeds 90% threshold). 12.34 GB free
OK: Disk usage at 74.3% on /tmp (25.67 GB free)

How it works

The script uses shutil.disk_usage() which returns a named tuple with total, used, and free bytes. The percentage is calculated as used divided by total multiplied by 100. The function compares this percentage against the provided threshold, returning either an ALERT or OK string. Formatting with :.1f rounds the percentage to one decimal place, and 1024**3 converts bytes to gigabytes for readable free space. The if __name__ == '__main__': block ensures the checks only run when executed directly, not when imported.

Common mistakes

  • Forgetting to multiply by 100 when calculating percentage
  • Using integer division which truncates the percentage
  • Hardcoding paths instead of accepting threshold parameters

Variations

  1. Use `os.statvfs()` for cross-platform filesystem stats
  2. Return a boolean flag alongside the message for easy scheduling integration

Real-world use cases

  • Running as a cron job on a server to alert DevOps before disks fill up.
  • Integrating with monitoring tools like Prometheus exporters to expose disk metrics.
  • Triggering cleanup scripts automatically when usage crosses a safe threshold.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.