Lesson · Capstone Core-Python Skills
Build a Command-Line Program
153 min readBuild a Command-Line Program
This capstone combines argument parsing, modules, files, validation, logging, exceptions, and tests into one command-line application. The emphasis is on a maintainable boundary between CLI code and reusable logic.
Learning goals
- Lay out a CLI project so
cli.pyconverts text into validated values and never holds domain rules. - Write at least three subcommands whose handlers produce useful exit codes, with help text a user can act on.
- Keep persistence in
storage.pyso tests can exercise the service without starting the CLI or touching real files. - Raise and catch custom exceptions at the application boundary so invalid input produces one concise error instead of a traceback.
- Add logging for startup and failures without logging secrets or one line per loop iteration.
Mental model
The boundary is the point of the design: cli.py owns text and exit codes, service.py owns decisions on typed values, and storage.py owns the file format, so each module can be imported and tested alone. Exceptions travel back across the boundary and turn into concise messages, and logging records what happened without carrying secrets. When a concern lands in the wrong layer, the symptom is usually a test that needs the whole application to check one rule.
Mental model
read it top to bottom
argv text (str) ↓ argparse in cli.py: parse and validate plain Python values ↓ service.py: use cases, no argv, no file handles results as ordinary collections ↓ storage.py: JSON or file persistence, safe resource handling exit code, one concise message, log lines for the important events
Core idea
The capstone's real subject is boundaries: keep argv, files, and exit codes at the edges so the middle stays importable, testable Python, with layers that communicate through plain values and named exceptions. A maintainable CLI is less about any single library call and more about where each decision lives; argparse, logging, and persistence are all deliberately thin at the edge.
Modules
A module is any importable .py file, and a package is a directory of modules marked with __init__.py. In this capstone the module split is the architecture: cli.py, service.py, and storage.py each expose one concern, so a test can import the service without starting the command line. Whatever a module runs at the top level happens at import time, which is why the program entry point belongs behind if __name__ == "__main__":.
Functions
Functions are the units the layers exchange work through: the CLI parses text and calls service functions with plain Python values, and those functions return results or raise named exceptions. Keeping them independent of sys.argv and open file handles is what makes them importable and directly testable. A function that needs the command line in order to run has placed the boundary in the wrong layer.
Collections
Collections are the plain data shapes the layers pass between each other: a list preserves the order of records to display, a dict gives lookup by key, and a tuple fixes a group that must not change. Using ordinary collections at the service boundary keeps the CLI, storage, and tests able to consume results without sharing mutable state by accident. Choose the type from the access pattern, and return a new collection when callers must not see later mutation.
File I/O
File I/O is the capstone's persistence layer, and it lives in storage.py behind functions such as load_tasks and save_tasks. Read and write with with open(...) (or Path.read_text and Path.write_text) so the handle closes even when an exception interrupts the body, and let FileNotFoundError or json.JSONDecodeError surface as the failures the boundary translates into concise errors. Keeping the format in one module also lets tests point storage at a temporary directory instead of the real one.
Exceptions
Exceptions in a CLI divide into expected failures (a missing file, a malformed number, an unknown task id) and bugs that should crash loudly with their traceback. The boundary catches the first kind, prints one actionable message, and returns a non-zero exit code, while the second kind is allowed to propagate. Custom exception classes give the service vocabulary for naming its failures without knowing anything about argparse or printing.
Logging
Log lifecycle events, failures, retries, and high-level progress with enough context to identify the work item. Avoid logging secrets or producing one log event for every tight-loop operation unless diagnostics require it.
Argument parsing
Parse command-line text at the application boundary and convert it into validated Python values before calling reusable logic. Keep argparse concerns out of domain functions.
Testing
Tests for a CLI should cover reusable logic directly and add a smaller number of integration tests for argument parsing, filesystem behavior, and exit status.
Walkthrough
src/tasker/is the importable package:__init__.pymarks the directory as a package, and everything under it can be imported by tests without ever running the CLI.cli.pyowns the argparse boundary: it converts command-line text into validated Python values (paths, counts, modes) and passes them toservice.py; domain rules do not belong here.service.pyholds the use cases as functions over plain values, which is whytests/test_service.pycan exercise them directly, with no argument parsing and no real files involved.storage.pyowns the JSON and file-format concern, including safe resource handling, socli.pynever opens a file itself and a format change stays in one module. Predict before building: when a test for a rule would need argparse or a real file, which module the rule actually belongs in.
Experiments to try
- Restructure a single-file script into the three-module layout from the example and prove that a test can import the service and call one use case with plain values.
- Add two subcommands to
cli.py, then run--helpfor the program and for each subcommand; record what each page shows and the exit code of each run. - Move one validation rule from an argparse callback into the service, call the service directly with a bad value, and confirm the error still identifies the input that failed.
- Run each subcommand against a missing or unreadable path and record the default output and exit status; then compare with the traceback a re-raised error would produce and decide which one a user should see.
Capstone specification
Build a command-line application with at least three subcommands.
Common mistakes
- Putting domain rules in argparse (a
choiceslist ortype=callback that enforces business constraints): the rule then exists only when the command-line parser runs, so other callers and tests cannot rely on it, and argparse's error formatting leaks into domain feedback. - Letting
cli.pyopen files or know the JSON shape: persistence spread across layers forces tests to use real files and makes a format change touch the CLI; the format belongs instorage.pybehind functions. - Printing a traceback for expected user errors: a missing file or a malformed number is an ordinary outcome, and a stack trace buries the one line the user needs; catch the named exception at the boundary, print a message, and return a non-zero exit code.
- Testing only through subprocess runs of the CLI: end-to-end tests are valuable but slow and indirect for validation rules; unit-test the service directly and keep a small number of integration tests for parsing, files, and exit codes.
Practice: Easy
- Create the three-module layout from the worked example and confirm that a test file can import
serviceand call one use case without runningcli.py. - Add
addandlistsubcommands tocli.py, then run--helpfor the program and for each subcommand; record what each page shows and the exit code of each run. - Call a service function directly with an invalid value and record the exception; then feed the same value through the CLI and record the message and exit status.
Practice: Medium
- Move one validation rule out of an argparse
type=callback into the service function, and show that the direct call and the CLI path now fail identically. - Add a custom exception such as
TaskNotFoundError, raise it from the service, catch it incli.py, and print one line with exit status 1; test both the direct raise and the CLI output. - Point
storage.pyat atempfile.TemporaryDirectory()in a test and show the service round trip works without touching the project's real data file.
Practice: Hard
- Implement the capstone specification for one small domain: three subcommands, configuration separated from logic, file persistence, custom exceptions, startup and failure logging, unit tests for the service, one end-to-end test that checks an exit code, and a README with usage.
- Add a
--verboseflag that raises the logging level, then write two integration tests asserting what appears at each level; confirm no message contains a secret-like value. - Review the architecture against the evaluation questions: import the core logic without argparse, feed invalid input and capture the error instead of a traceback, and replace the filesystem boundary in a test; record which layer had to change for each.
Lesson checklist
- I can put argparse in
cli.py, decisions inservice.py, and the file format instorage.py, and say why each binds there. - I can run any subcommand with
--helpand explain the exit codes the program returns. - I can make an expected failure print one concise message with a non-zero status instead of a traceback.
- I can test domain logic by importing the service, without starting the CLI or touching real files.
Remember
A maintainable CLI is an exercise in boundaries: argparse converts text into validated values at the edge, the service makes decisions on those values, storage owns the file format, and the boundary turns named exceptions into concise messages and exit codes. The capstone's evaluation questions (importable core, single-line errors, swappable filesystem, focused tests) all measure how well those layers stayed separate.
Interview angles
What is the main purpose of **Modules**?+
A module is an importable .py file, and this project splits its concerns into cli.py, service.py, and storage.py so each can be imported alone. The split is what lets tests/test_service.py exercise the use cases without argparse or a real filesystem.
What should you pay attention to when using **Functions**?+
Functions are how work crosses the layers: the CLI parses text, then calls service functions with plain Python values, and they return results or raise named exceptions. Keeping them free of sys.argv and open file handles is what makes them importable and testable on their own.
How does **Collections** fit into this lesson?+
Collections are the plain values the service returns and the other layers consume: a list for ordered records, a dict for lookup by key, a tuple for a fixed group. Passing ordinary collections keeps the CLI, storage, and tests decoupled from each other's internal state.
Why should domain validation live in `service.py` instead of an argparse `type=` callback?+
Validation placed in argparse exists only when the command-line parser runs, so the service cannot rely on it and tests must parse arguments to exercise the rule. Keeping the rule in the service gives every caller (the CLI, tests, future callers) the same behavior, and argparse stays a thin text-to-values boundary.