#!/usr/bin/env python3
import os
import sys
import argparse
from pathlib import Path
import shutil
from collections import defaultdict
def format_bytes(size, human=True):
"""
Format a byte size to human readable or raw bytes.
"""
if not human:
return f"{size:,} B"
if size == 0:
return "0 B"
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
i = 0
while size >= 1024 and i < len(units) - 1:
size /= 1024.0
i += 1
return f"{size:6.1f} {units[i]}"
def get_sizes(start_path, files=False, hidden=False):
"""
Calculate sizes of directories (subtree) or files in the given path.
"""
start = Path(start_path).resolve()
sizes = defaultdict(int)
try:
for root, dirs, files_list in os.walk(start):
# Prune hidden directories unless --hidden
dirs[:] = [d for d in dirs if hidden or not d.startswith('.')]
rootp = Path(root)
for f in files_list:
fp = rootp / f
try:
size = os.path.getsize(fp)
if files:
sizes[str(fp)] = size
else:
# Add file size to all ancestor directories (subtree sizes)
current = fp.parent
while str(current) != str(start):
sizes[str(current)] += size
current = current.parent
# Include in root
sizes[str(start)] += size
except (OSError, PermissionError):
pass
except (OSError, PermissionError):
pass
return sizes
def print_disk(path_str, bytes_flag=False):
"""
Print disk usage for the given path.
"""
path = Path(path_str).resolve()
if not path.exists():
print(f"Error: Path does not exist: {path}", file=sys.stderr)
sys.exit(1)
total, used, free = shutil.disk_usage(path)
human = not bytes_flag
print(f"Disk usage for {path}:")
print(f"Total: {format_bytes(total, human)}")
print(f"Used: {format_bytes(used, human)}")
print(f"Free: {format_bytes(free, human)}")
print(f"Used: {used / total * 100:5.1f}%")
def print_scan(path_str, top, files_flag, hidden_flag, bytes_flag):
"""
Print top largest files or directories.
"""
start = Path(path_str).resolve()
if not start.exists() or not start.is_dir():
print(f"Error: Not a directory: {start}", file=sys.stderr)
sys.exit(1)
print(f"Scanning {start}... (this may take a while for large directories)")
sizes = get_sizes(start, files=files_flag, hidden=hidden_flag)
if not sizes:
print("No sizes collected (possibly due to permissions).")
return
sorted_items = sorted(sizes.items(), key=lambda x: x[1], reverse=True)[:top]
what = "files" if files_flag else "directories"
print(f"\nTop {top} largest {what} in {start}:")
print("-" * 80)
for name, size in sorted_items:
p = Path(name)
try:
rel = p.relative_to(start)
rel_str = f"./{rel}" if rel != '.' else '.'
except ValueError:
rel_str = str(p)
print(f"{format_bytes(size, human=not bytes_flag)} {rel_str}")
total_str = format_bytes(sum(sizes.values()), human=not bytes_flag)
print("-" * 80)
print(f"Total scanned: {total_str}")
def main():
parser = argparse.ArgumentParser(
description="Disk usage analyzer CLI tool.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s disk /
%(prog)s disk . --bytes
%(prog)s scan /home --top 5
%(prog)s scan . --files --hidden
"""
)
parser.add_argument('--version', action='version', version='%(prog)s v1.0')
subparsers = parser.add_subparsers(dest='command', required=True)
# Disk command
disk_parser = subparsers.add_parser('disk', help='Show overall disk usage for a filesystem')
disk_parser.add_argument('path', nargs='?', default='.', help='Path (default: current directory)')
disk_parser.add_argument('--bytes', '-b', action='store_true', help='Show raw byte counts instead of human-readable')
# Scan command
scan_parser = subparsers.add_parser('scan', help='Scan directory and show top largest files or directories')
scan_parser.add_argument('path', nargs='?', default='.', help='Directory to scan (default: current directory)')
scan_parser.add_argument('--top', '-t', type=int, default=20, help='Number of top items to show (default: 20)')
scan_parser.add_argument('--files', '-f', action='store_true', help='Show top files instead of directories')
scan_parser.add_argument('--hidden', '-H', action='store_true', help='Include hidden directories/files')
scan_parser.add_argument('--bytes', '-b', action='store_true', help='Show raw byte counts instead of human-readable')
args = parser.parse_args()
if args.command == 'disk':
print_disk(args.path, args.bytes)
elif args.command == 'scan':
print_scan(args.path, args.top, args.files, args.hidden, args.bytes)
if __name__ == '__main__':
main()
Installation and Usage
-
Save the script: Save the code above as disk_analyzer.py.
-
Make it executable (Unix/macOS):
chmod +x disk_analyzer.py
-
Run examples:
python3 disk_analyzer.py disk /
python3 disk_analyzer.py scan /home/user --top 10 --files
python3 disk_analyzer.py scan . --hidden
python3 disk_analyzer.py disk --help
Features
- disk: Shows total/used/free space and usage percentage for the filesystem containing the path (like
df).
- scan: Recursively scans a directory:
- Directories (default): Subtree sizes (total size of all contents recursively).
- Files (
--files): Individual file sizes.
- Top N items sorted by size descending.
- Human-readable sizes by default (KiB, MiB, etc.).
- Skips hidden directories (
.git, etc.) by default; use --hidden to include.
- Relative paths for readability.
- Cross-platform (Linux, macOS, Windows).
- Handles permission errors gracefully.
- No external dependencies (pure stdlib).
Notes:
- Scanning large directories (e.g.,
/) can take time and memory.
- Directory sizes include all nested files but exclude directory metadata itself.
- Symlinks to directories are not followed (
os.walk(followlinks=False)).