Designing a disk usage analyzer
The user wants a Python CLI tool for analyzing disk usage. It’s a bit ambiguous whether they need code or a design, and they didn't specify an OS. I’m thinking it might be similar to commands like 'du' or 'df' and could use the psutil library.
I should design a command-line interface with options such as showing disk usage per directory, sorting, filtering, and supporting JSON or human-readable formats. While I can provide a working example using argparse, I might need to ask for further clarification on some details.Designing disk usage tool
I could include psutil for filesystem-level stats, but since the user mentioned "disk usage statistics," we should interpret that as file space per directory. I can cover both overall disks and per-path analysis by designing a command like 'diskusage' with subcommands.
We might have 'summary' for an overview (similar to df) and 'scan' for detailed usage (like du). Using argparse with subparsers makes sense here. To get disk summary, I could utilize shutil.disk_usage, which avoids third-party dependencies unless the user prefers otherwise.Implementing directory scanning
For scanning directories, I’m thinking of recursively walking through them and creating a dictionary that maps each path to its total size. One approach would be to add each file's size to its parent directory. This method has a complexity of O(depth*files), which is manageable for smaller scales.
Alternatively, I could treat each directory separately and sum the sizes of immediate files and subdirectories, though that would require repeated traversals. Using os.walk(topdown=False will help compute child directory sizes first when visiting a directory, so I'll go with that.Refining directory scanning
I’ve decided to use topdown=True while tracking depth. This way, if the depth reaches max_depth, I can set dirs[:] to an empty list to skip deeper traversal. However, the 'max-depth' parameter might only apply to display, not scanning. So, for accuracy, I should scan everything and then filter the output by depth.
I’ll use os.walk(root, topdown=True) and initialize a dictionary for directory sizes. As I iterate through each file, I'll sum their sizes and catch any errors. Then, I'll add the sizes of child directories to their parent, ultimately calculating the total size for the root directory.Building a disk usage CLI tool
I’m implementing a Python CLI tool to analyze disk usage, with features like showing the top heavy directories, setting a minimum size threshold, and providing formats like table or JSON. The tool will allow for human-readable sizes and an option to include largest files.
The script will include a core function to scan directories, handle errors, and compute sizes using os and shutil. I’ll set up argparse for user commands, ensuring everything is simple yet effective. The implementation will allow filtering by size and outputting results in a clear format.
Here’s a code outline:
#!/usr/bin/env python3
import argparse, os, shutil, json, sys
from collections import defaultdict
def human_readable(num, si=False):
unit = 1000 if si else 1024
...
def parse_size(s):
...
def scan_directory(path, follow_symlinks=False, exclude_hidden=True):
path = os.path.abspath(path)
dir_sizes = defaultdict(int)
file_sizes = {}
errors = []
for root, dirs, files in os.walk(path, topdown=False, followlinks=follow_symlinks):
...
return path, dir_sizes, file_sizes, errors
# Additional argparser setup and command handling
For usage, provide examples for running the script and explain installation via pip if needed. Below is a self‑contained Python CLI tool that analyzes disk usage. It includes:
- A
summary command (like df for one path).
- A
scan command (like a simplified du with sorting and filters).
You can save this as diskusage.py and run with python diskusage.py ... or turn it into an installable CLI.
Code: diskusage.py
#!/usr/bin/env python3
"""
diskusage.py - Simple disk usage analysis CLI.
Usage examples:
# Show disk summary for current directory
python diskusage.py summary
# Show disk summary for /var
python diskusage.py summary /var
# Scan current directory and show top 20 directories by size
python diskusage.py scan .
# Show top 50 directories, human-readable sizes
python diskusage.py scan . --top 50 -H
# Show top 20 files only
python diskusage.py scan . --by files
# Limit output depth to 2 levels
python diskusage.py scan . --depth 2
# Output JSON instead of a table
python diskusage.py scan . --json
# Only show entries >= 100 MB
python diskusage.py scan . --min-size 100M
"""
import argparse
import json
import os
import shutil
import sys
from collections import defaultdict
from typing import Dict, List, Tuple, Optional
# ---------- Helpers ----------
def human_readable_size(num_bytes: int, si: bool = False) -> str:
"""
Convert a size in bytes to a human-readable string.
si=False (default) -> powers of 1024, units KiB, MiB, ...
si=True -> powers of 1000, units kB, MB, ...
"""
if num_bytes is None:
return "0 B"
unit = 1000 if si else 1024
if num_bytes < unit:
return f"{num_bytes} B"
exp = 0
num = float(num_bytes)
while num >= unit and exp < 6:
num /= unit
exp += 1
suffixes = ["B",
"kB" if si else "KiB",
"MB" if si else "MiB",
"GB" if si else "GiB",
"TB" if si else "TiB",
"PB" if si else "PiB",
"EB" if si else "EiB"]
return f"{num:.1f} {suffixes[exp]}"
def parse_size(size_str: str) -> int:
"""
Parse a human-readable size string into bytes.
Accepts examples like:
"1024" -> 1024 bytes
"10K" -> 10 * 1024
"5M" -> 5 * 1024**2
"1G" -> 1 * 1024**3
Units are case-insensitive. Uses binary (1024-based) units.
"""
s = size_str.strip().lower()
if not s:
raise ValueError("Empty size string")
units = {
"k": 1024**1,
"m": 1024**2,
"g": 1024**3,
"t": 1024**4,
"p": 1024**5,
"e": 1024**6,
}
# If last char is alphabetic, treat as unit
if s[-1].isalpha():
unit_char = s[-1]
if unit_char not in units:
raise ValueError(f"Unknown size unit '{size_str[-1]}' in '{size_str}'")
number_part = s[:-1]
if not number_part:
raise ValueError(f"Missing number in size '{size_str}'")
value = float(number_part)
return int(value * units[unit_char])
else:
# Plain bytes
return int(s)
# ---------- Disk summary ----------
def cmd_summary(path: str, human: bool, si: bool) -> int:
"""
Show total, used, and free space for the filesystem containing 'path'.
"""
abs_path = os.path.abspath(path)
if not os.path.exists(abs_path):
print(f"Error: path does not exist: {abs_path}", file=sys.stderr)
return 1
total, used, free = shutil.disk_usage(abs_path)
used_pct = (used / total * 100) if total > 0 else 0.0
free_pct = (free / total * 100) if total > 0 else 0.0
def fmt(b: int) -> str:
return human_readable_size(b, si=si) if human else f"{b} B"
print(f"Disk usage for: {abs_path}")
print("-" * 60)
print(f" Total: {fmt(total)}")
print(f" Used : {fmt(used)} ({used_pct:.1f}%)")
print(f" Free : {fmt(free)} ({free_pct:.1f}%)")
print("-" * 60)
return 0
# ---------- Directory scan ----------
def scan_directory(
path: str,
follow_symlinks: bool = False,
exclude_hidden: bool = True
) -> Tuple[str, Dict[str, int], Dict[str, int], List[Tuple[str, str]]]:
"""
Recursively scan a directory tree, computing total size per directory
and size per file.
Returns (root_path, dir_sizes, file_sizes, errors)
- root_path: absolute root path scanned
- dir_sizes: {directory_path: total_size_of_all_files_under_it}
- file_sizes: {file_path: file_size}
- errors: list of (path, error_message) for any files/dirs that
could not be accessed
"""
root = os.path.abspath(path)
dir_sizes: Dict[str, int] = defaultdict(int)
file_sizes: Dict[str, int] = {}
errors: List[Tuple[str, str]] = []
# Walk bottom-up so we can aggregate child dir sizes into parents
for current_root, dirs, files in os.walk(
root,
topdown=False,
followlinks=follow_symlinks
):
# Optionally filter out hidden directories and files
if exclude_hidden:
dirs[:] = [d for d in dirs if not d.startswith(".")]
files = [f for f in files if not f.startswith(".")]
# Sum file sizes in the current directory
for filename in files:
file_path = os.path.join(current_root, filename)
try:
st = os.stat(file_path, follow_symlinks=follow_symlinks)
size = st.st_size
except (OSError, PermissionError) as e:
errors.append((file_path, str(e)))
continue
file_sizes[file_path] = size
dir_sizes[current_root] += size
# Aggregate child directory sizes
for d in dirs:
child_dir = os.path.join(current_root, d)
dir_sizes[current_root] += dir_sizes.get(child_dir, 0)
return root, dict(dir_sizes), file_sizes, errors
def format_table(
root: str,
entries: List[Tuple[str, int]],
human: bool,
si: bool,
max_depth: Optional[int] = None
) -> str:
"""
Format (path, size) entries as a simple text table limited to
a given max_depth from the root (if provided).
"""
if not entries:
return "(no entries)\n"
lines = []
root = os.path.abspath(root)
root_with_sep = root + os.sep
def depth_of(path: str) -> int:
if path == root:
return 0
rel = path[len(root_with_sep):] if path.startswith(root_with_sep) else os.path.relpath(path, root)
if rel == ".":
return 0
return rel.count(os.sep) + 1
# Filter by depth
if max_depth is not None:
entries = [(p, s) for p, s in entries if depth_of(p) <= max_depth]
# Determine column widths
size_col = "Size"
path_col = "Path"
def fmt_size(s: int) -> str:
return human_readable_size(s, si=si) if human else str(s)
size_strings = [fmt_size(s) for _, s in entries]
max_size_width = max(len(size_col), *(len(ss) for ss in size_strings))
max_path_width = max(len(path_col), *(len(p) for p, _ in entries))
header = f"{size_col:>{max_size_width}} {path_col}"
lines.append(header)
lines.append("-" * len(header))
for (path, size), size_str in zip(entries, size_strings):
lines.append(f"{size_str:>{max_size_width}} {path}")
return "\n".join(lines) + "\n"
def cmd_scan(
path: str,
top: int,
by: str,
min_size_str: Optional[str],
depth: Optional[int],
human: bool,
si: bool,
as_json: bool,
include_hidden: bool,
follow_symlinks: bool
) -> int:
"""
Scan a directory tree and report largest directories and/or files.
"""
abs_path = os.path.abspath(path)
if not os.path.exists(abs_path):
print(f"Error: path does not exist: {abs_path}", file=sys.stderr)
return 1
root, dir_sizes, file_sizes, errors = scan_directory(
abs_path,
follow_symlinks=follow_symlinks,
exclude_hidden=not include_hidden
)
# Apply minimum size filter if requested
min_size = 0
if min_size_str:
try:
min_size = parse_size(min_size_str)
except ValueError as e:
print(f"Error parsing --min-size: {e}", file=sys.stderr)
return 1
def size_filter(items: Dict[str, int]) -> List[Tuple[str, int]]:
return [(p, s) for p, s in items.items() if s >= min_size]
dir_entries: List[Tuple[str, int]] = []
file_entries: List[Tuple[str, int]] = []
if by in ("dirs", "both"):
dir_entries = size_filter(dir_sizes)
dir_entries.sort(key=lambda x: x[1], reverse=True)
if top:
dir_entries = dir_entries[:top]
if by in ("files", "both"):
file_entries = size_filter(file_sizes)
file_entries.sort(key=lambda x: x[1], reverse=True)
if top:
file_entries = file_entries[:top]
if as_json:
output = {
"root": root,
"by": by,
"top": top,
"min_size": min_size,
"human_readable": human,
"si_units": si,
"directories": [{"path": p, "size": s} for p, s in dir_entries],
"files": [{"path": p, "size": s} for p, s in file_entries],
"errors": [{"path": p, "error": msg} for p, msg in errors],
}
print(json.dumps(output, indent=2))
return 0
# Human-readable text output
if by in ("dirs", "both"):
print(f"Top {len(dir_entries)} directories by size under: {root}")
print(format_table(root, dir_entries, human=human, si=si, max_depth=depth))
if by in ("files", "both"):
print(f"Top {len(file_entries)} files by size under: {root}")
print(format_table(root, file_entries, human=human, si=si, max_depth=depth))
if errors:
print(f"Encountered {len(errors)} errors while scanning (permissions, etc.).", file=sys.stderr)
return 0
# ---------- CLI parsing ----------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Analyze disk usage statistics (summary and per-directory/file scan).",
)
parser.add_argument(
"-H", "--human-readable",
action="store_true",
help="Print sizes in human-readable format (powers of 1024)."
)
parser.add_argument(
"--si",
action="store_true",
help="Use SI units (powers of 1000) instead of 1024 when human-readable."
)
subparsers = parser.add_subparsers(dest="command", required=True)
# summary command
p_summary = subparsers.add_parser(
"summary",
help="Show disk usage summary (total, used, free) for a path's filesystem."
)
p_summary.add_argument(
"path",
nargs="?",
default=".",
help="Path whose containing filesystem to summarize (default: current directory)."
)
# scan command
p_scan = subparsers.add_parser(
"scan",
help="Scan a directory tree and show largest directories and files."
)
p_scan.add_argument(
"path",
nargs="?",
default=".",
help="Root directory to scan (default: current directory)."
)
p_scan.add_argument(
"--top",
type=int,
default=20,
help="Maximum number of entries per category to show (default: 20)."
)
p_scan.add_argument(
"--by",
choices=["dirs", "files", "both"],
default="dirs",
help="Show largest directories, files, or both (default: dirs)."
)
p_scan.add_argument(
"--min-size",
type=str,
default=None,
help="Only include entries at least this large (e.g. 10M, 1G)."
)
p_scan.add_argument(
"--depth",
type=int,
default=None,
help="Maximum depth from the root to show (0=root, 1=children, etc.)."
)
p_scan.add_argument(
"--json",
action="store_true",
help="Output results as JSON instead of a text table."
)
p_scan.add_argument(
"--include-hidden",
action="store_true",
help="Include hidden files and directories (starting with '.')."
)
p_scan.add_argument(
"--follow-symlinks",
action="store_true",
help="Follow symbolic links when scanning (may cause loops)."
)
return parser
def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
human = args.human_readable
si = args.si
if args.command == "summary":
return cmd_summary(args.path, human=human, si=si)
elif args.command == "scan":
return cmd_scan(
path=args.path,
top=args.top,
by=args.by,
min_size_str=args.min_size,
depth=args.depth,
human=human,
si=si,
as_json=args.json,
include_hidden=args.include_hidden,
follow_symlinks=args.follow_symlinks,
)
parser.error("Unknown command") # Should never reach here
return 1
if __name__ == "__main__":
raise SystemExit(main())
Basic usage
From the directory where diskusage.py is stored:
# Summary of the filesystem that "." is on
python diskusage.py summary
# Summary of the filesystem that /var is on
python diskusage.py summary /var
# Scan current directory, top 20 directories by size
python diskusage.py scan .
# Scan with human-readable sizes and show both directories and files
python diskusage.py scan . --by both -H
# JSON output suitable for scripting
python diskusage.py scan . --json
If you want this as a global CLI command, you can:
-
Make it executable (on Unix-like systems):
chmod +x diskusage.py
-
Put it on your PATH (or add a small wrapper script / install it as a package later).
If you want, I can also show how to turn this into a pip-installable package with a diskusage console script.