brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's shutil.disk_usage reads free disk space without parsing df

Python
~/tips/tip-python-shutil-disk-usage

import shutil

Get total, used and free bytes for any mount point straight from Python.

For a small script that warns when a disk fills up, parsing df output feels fragile to me. Python has the numbers directly.

import shutil

usage = shutil.disk_usage("/")
free_pct = usage.free / usage.total
print(f"{usage.free / 1e9:.1f} GB free ({free_pct:.0%})")
if free_pct < 0.10:
    print("less than 10 percent free")

disk_usage returns a named tuple with total, used and free, all in bytes. Pass it any path and you get the numbers for the filesystem that path lives on, so disk_usage("/mnt/backup") checks the backup disk and not the root one.

I find this nicer than df because there are no columns to split and no locale or line wrapping to worry about when a device name is long.

Don’t expect used plus free to add up to total. On Linux, free is the space a normal user can still write, and ext4 keeps a few percent reserved for root. On a Mac with APFS the numbers are even further apart because volumes share one container. For a warning threshold, compare free against total like above and leave used out of it.

Further reading: shutil.disk_usage

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link