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.
Python code
17 linesimport 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
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
- Use `os.statvfs()` for cross-platform filesystem stats
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.