Lesson 20: Capstone — Build and Ship a Command-Line Tool
Everything in this course converges on one skill: building a tool that someone else can actually use. Your capstone is a command-line program called wordcount — a small utility that counts lines, words and characters in a text file, like the classic Unix wc command. It is small enough to finish in one sitting, but it uses nearly everything you have learned: classes to hold the counts, generators to stream the file without loading it, argparse for a proper command-line interface, tests to prove it works, and a package layout so it can be installed and run from anywhere.
The heart of the tool is a generator. Instead of reading the whole file into memory, the program yields one line at a time and updates the counts as it goes — the lazy pipeline pattern from Lesson 8, applied to a real job. The counts themselves live in a small class with a __str__ method, so printing the result looks clean. And argparse turns the script into a real command-line tool: flags such as -l, -w and -c choose which counts to show, and --help prints a usage message automatically, for free.
import argparse
import sys
class Counts:
def __init__(self):
self.lines = 0
self.words = 0
self.chars = 0
def add_line(self, line):
self.lines += 1
self.words += len(line.split())
self.chars += len(line)
def __str__(self):
return f"{self.lines} lines, {self.words} words, {self.chars} chars"
def count_file(path):
counts = Counts()
with open(path, encoding="utf-8") as f:
for line in f: # the file yields one line at a time
counts.add_line(line)
return counts
def main(argv=None):
parser = argparse.ArgumentParser(
prog="wordcount", description="Count lines, words and chars in a file.")
parser.add_argument("path", help="the text file to count")
parser.add_argument("-l", "--lines", action="store_true")
parser.add_argument("-w", "--words", action="store_true")
args = parser.parse_args(argv)
counts = count_file(args.path)
if not (args.lines or args.words):
print(counts)
else:
if args.lines:
print("lines:", counts.lines)
if args.words:
print("words:", counts.words)
if __name__ == "__main__":
main()
Shipping it: tests, packaging, and the finish line
A tool is not finished when it runs on your machine — it is finished when it runs on someone else's. That means three last steps. First, write tests: a test that counts a small known file and checks the numbers, a test for an empty file, and a test that a missing file raises FileNotFoundError. Run them with pytest or unittest, and keep them in the repository. Second, add a pyproject.toml that names the project and declares a console entry point, so that installing the package creates a real wordcount command on the user's path. Third, commit it all to Git with a clear message, and push it somewhere others can find it.
Then step back and look at what you have built across these twenty lessons. You can design classes that model real things, write lazy pipelines that handle data of any size, wrap behaviour with decorators, protect resources with context managers, prove your code with tests, type it so others can read it, speed it up with threads and processes, and ship it as a package with version control. That is the working toolkit of a Python developer. The next step is not another course — it is a project of your own, built with these tools, tested, packaged, and shared. Pick something you actually want to exist, and build it.
Going further
A shipped tool also needs a README: a short file explaining what the tool does, how to install it, and how to use it, with an example. The README is often the first thing another person reads, and a good one answers three questions in under a minute: what is this, why would I want it, and what do I type to run it? Include the example commands and their expected output, so a new user can check their installation works. A tool without a README is a tool nobody will try twice.
The capstone also leaves room to grow, and that is deliberate. You could add a --sort flag, a --top option to show the most common words, or support for reading from standard input so the tool works in a pipeline. Each addition is a small, well-defined job: a new argument in the parser, a new method on the counts class, and a new test. That is how real tools grow — one small, tested feature at a time — and it is a good model for whatever you build next.
Before you call the capstone finished, try using the tool the way a stranger would: install it in a fresh virtual environment, run wordcount --help, and count a file you did not create. Every point of confusion you hit is a real defect in the tool — a missing instruction, an unclear error, a flag that does not do what its name promises — and fixing those is the difference between a program that works for its author and a tool that works for anyone. That final test, done with fresh eyes, is the most valuable hour you will spend on any project.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Argparse for CLI - Intermediate Python Programming p.3 — sentdex
Harrison Kinsley (sentdex) builds a command-line interface with argparse, the same module your capstone tool uses for its flags and arguments.
Key Terms
- argparse
- The standard-library module for building command-line interfaces with flags, arguments and automatic --help.
- Command-line tool (CLI)
- A program run from the terminal, taking arguments and flags instead of a graphical interface.
- Entry point
- A declaration in pyproject.toml that creates a command (such as wordcount) when a package is installed.
- Console script
- A command installed on the user's path by a package, which runs a Python function.
- store_true
- An argparse action that sets a flag to True when present on the command line.
- Ship
- To package, test and publish a tool so others can install and use it.
- Capstone
- A final project that brings together the skills of a whole course in one working piece.
Discussion Questions
- Why does count_file read the file one line at a time instead of loading it all with read()? What would break on a very large file?
- What three tests would you write for wordcount before calling it done? What edge cases matter most?
- What project of your own would you like to build next, and which tools from this course would it need?
Practice Questions
- What does
parser.add_argument("-l", "--lines", action="store_true")do? - What does
wordcount myfile.txtprint if no flags are given? - Why does
main()take anargv=Noneparameter? - What happens if the file does not exist?
- What three steps make the tool shippable to someone else?
Show answers
- It adds a -l / --lines flag that sets args.lines to True when given. With store_true, the flag takes no value — its presence is the value.
- The full summary, such as "3 lines, 24 words, 150 chars". When neither flag is set, main() prints the whole Counts object via __str__.
- So tests can pass a fake argument list. parse_args(None) reads the real command line; passing a list lets a test drive the tool without a terminal.
- open() raises FileNotFoundError. A good follow-up would be to catch it and print a friendly error — or let it propagate, as the capstone does.
- Tests, a pyproject.toml with an entry point, and a Git commit. Together they prove it works, make it installable as a command, and record it for sharing.