Lab: Rich tool
Upgrade a plain-text file-scanner script to use Rich tables, a progress bar, and error panels.
- Rewrite a plain-text CLI tool to use Rich tables for structured results
- Add a progress bar during the scanning phase
- Use Panel to frame error messages clearly
This lab starts with a working but plain file-scanner script and walks through four incremental upgrades. Each step is independent — you can run the demo after each one to see the difference.
The goal is not just to learn the Rich API. It is to practise the judgment call: when does formatting help users, and when is it noise?
The starting point
Here is the script as it exists before any Rich:
It works. It prints results. But finding the file with the most blank lines requires reading every line of output.
Step 1 — Replace print() with rich.print()
The smallest possible upgrade: swap print for rich.print and add colour to
the status lines. No structural change, just improved scanability:
The error line is now unmissable. File names are highlighted. Blank counts are
de-emphasised with [dim] since they are secondary detail.
Step 2 — Add a progress bar
The scanner iterates over files. Wrap that loop in rich.progress.track():
One-word change to the loop. The user now sees progress even with three files — and when the list grows to 300, they see exactly where the scan is.
Step 3 — Display results as a Table
The final output is the part that most benefits from structure:
Now results are scannable in a glance. The Lines column is right-aligned so
numbers line up. The Blank column is dimmed to indicate it is secondary.
Step 4 — Wrap errors in a Panel
When the scan encounters a directory that does not exist or cannot be read, the error should be impossible to miss:
Notice that the error message includes a recovery suggestion: "Run ds-tool init". Good error output always answers the question "what should I do now?" A Panel makes that suggestion impossible to overlook.
Putting it together
The four steps you just applied — coloured status lines, progress bar, results table, error panel — are the core of the Rich upgrade pattern. In a real tool you would apply all four at once. The individual steps are separated here so you can see the contribution each one makes.
The full upgraded tool is roughly 50 lines. The visual quality difference relative to the original 20-line version is significant. That ratio — a small amount of extra code for a large improvement in usability — is why Rich is worth the dependency.
Where to go next
Next module: Click and subcommands — moving from argparse to Click's decorator syntax to build multi-subcommand tools with shared state and automatic help generation.