Python Labs · Lab 2 of 6

Build, Test and Ship a Command-Line Tool

Write a real command-line tool with argparse subcommands, test it with pytest's capsys and tmp_path, give it an entry point, build a wheel and install it like any other tool.

Environment
Local
Level
Beginner
Time
About 40 min
Cost
Free

You will build

taskbox, a to-do list for the terminal with add, list and done commands, tested end to end, packaged as a wheel and installed with uv tool install.

Members can save this page, take notes and track progress. See membership · Sign in

Command-line tools have a contract with their users and with scripts: arguments, output on stdout, errors on
stderr and an exit status. This lab tests that contract directly.

The output below was recorded with uv 0.13.10 and Python 3.12. Newer versions print newer version numbers and timings; everything else should match. The finished-project download leaves out uv.lock: uv sync creates it.

Project structure

taskbox/
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
├── uv.lock
├── src/
│   └── taskbox/
│       ├── __init__.py
│       └── cli.py
└── tests/
    └── test_cli.py

Download finished project

Steps

  1. 1Create the project

    Run
    uv init --package taskbox
    cd taskbox
    uv add --dev pytest ruff
    
    Check:

    src/taskbox/__init__.py and uv.lock exist.

  2. 2Write the CLI

    Each subcommand is a function. Errors go to stderr with a non-zero exit status, so scripts can detect them; normal output goes to stdout. The task file is written to a temporary file and then renamed, so a crash can never leave it half-written.

    src/taskbox/cli.py
    """taskbox: a tiny to-do list for the terminal."""
    
    import argparse
    import json
    import os
    import sys
    from importlib.metadata import version
    from pathlib import Path
    
    DEFAULT_DB = Path.home() / ".taskbox.json"
    
    
    def load(db: Path) -> list[dict]:
        if not db.exists():
            return []
        return json.loads(db.read_text(encoding="utf-8"))
    
    
    def save(db: Path, tasks: list[dict]) -> None:
        # Write to a temporary file, then rename: a crash never leaves a half-written file.
        tmp = db.with_suffix(".tmp")
        tmp.write_text(json.dumps(tasks, indent=2), encoding="utf-8")
        tmp.replace(db)
    
    
    def cmd_add(args: argparse.Namespace, tasks: list[dict]) -> list[dict]:
        task_id = max((t["id"] for t in tasks), default=0) + 1
        task = {"id": task_id, "title": " ".join(args.title), "done": False}
        tasks.append(task)
        print(f"Added #{task_id}: {task['title']}")
        return tasks
    
    
    def cmd_list(args: argparse.Namespace, tasks: list[dict]) -> None:
        shown = [t for t in tasks if args.all or not t["done"]]
        if not shown:
            print("Nothing to do.")
        for t in shown:
            mark = "x" if t["done"] else " "
            print(f"[{mark}] #{t['id']} {t['title']}")
    
    
    def cmd_done(args: argparse.Namespace, tasks: list[dict]) -> list[dict]:
        for t in tasks:
            if t["id"] == args.id:
                t["done"] = True
                print(f"Done #{t['id']}: {t['title']}")
                return tasks
        print(f"taskbox: no task #{args.id}", file=sys.stderr)
        raise SystemExit(1)
    
    
    def build_parser() -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(prog="taskbox", description="A tiny to-do list.")
        parser.add_argument(
            "--db",
            type=Path,
            default=Path(os.environ.get("TASKBOX_DB", DEFAULT_DB)),
            help="task file (default: $TASKBOX_DB or ~/.taskbox.json)",
        )
        parser.add_argument("--version", action="version", version=f"%(prog)s {version('taskbox')}")
        sub = parser.add_subparsers(dest="command", required=True)
    
        add = sub.add_parser("add", help="add a task")
        add.add_argument("title", nargs="+")
        add.set_defaults(func=cmd_add)
    
        ls = sub.add_parser("list", help="show open tasks")
        ls.add_argument("-a", "--all", action="store_true", help="include finished tasks")
        ls.set_defaults(func=cmd_list)
    
        done = sub.add_parser("done", help="mark a task as finished")
        done.add_argument("id", type=int)
        done.set_defaults(func=cmd_done)
        return parser
    
    
    def main(argv: list[str] | None = None) -> int:
        args = build_parser().parse_args(argv)
        tasks = load(args.db)
        changed = args.func(args, tasks)
        if changed is not None:
            save(args.db, changed)
        return 0
    
    Hint

    Empty src/taskbox/__init__.py now: the entry point moves to taskbox.cli:main.

  3. 3Point the entry point at main()

    [project.scripts] creates a taskbox command when the package is installed.

    pyproject.toml
    [project]
    name = "taskbox"
    version = "0.1.0"
    description = "A tiny to-do list for the terminal"
    readme = "README.md"
    authors = [
        { name = "Your Name", email = "[email protected]" }
    ]
    requires-python = ">=3.12"
    dependencies = []
    
    [project.scripts]
    taskbox = "taskbox.cli:main"
    
    [build-system]
    requires = ["uv_build>=0.13.10,<0.14.0"]
    build-backend = "uv_build"
    
    [dependency-groups]
    dev = [
        "pytest>=9.2.0",
        "ruff>=0.17.6",
    ]
    
    [tool.ruff]
    line-length = 100
    
    [tool.ruff.lint]
    select = ["E", "F", "I", "B", "UP", "SIM"]
    
    [tool.pytest.ini_options]
    testpaths = ["tests"]
    
  4. 4Test the command-line contract

    tmp_path gives every test its own empty folder, so tests never touch your real task file. capsys captures stdout and stderr. SystemExit checks the exit status: 1 for our errors, 2 for usage errors from argparse.

    tests/test_cli.py
    import json
    
    import pytest
    
    from taskbox.cli import main
    
    
    @pytest.fixture
    def run(tmp_path):
        db = tmp_path / "tasks.json"
    
        def _run(*argv: str) -> int:
            return main(["--db", str(db), *argv])
    
        _run.db = db
        return _run
    
    
    def test_add_then_list(run, capsys):
        run("add", "Write", "tests")
        run("list")
        out = capsys.readouterr().out
        assert "Added #1: Write tests" in out
        assert "[ ] #1 Write tests" in out
    
    
    def test_done_hides_task_unless_all(run, capsys):
        run("add", "Ship it")
        run("done", "1")
        capsys.readouterr()
        run("list")
        assert capsys.readouterr().out == "Nothing to do.\n"
        run("list", "--all")
        assert capsys.readouterr().out == "[x] #1 Ship it\n"
    
    
    def test_tasks_are_saved_as_json(run):
        run("add", "Persist me")
        assert json.loads(run.db.read_text()) == [{"id": 1, "title": "Persist me", "done": False}]
    
    
    def test_unknown_task_exits_with_1(run, capsys):
        with pytest.raises(SystemExit) as exc:
            run("done", "9")
        assert exc.value.code == 1
        assert "no task #9" in capsys.readouterr().err
    
    
    def test_missing_command_is_a_usage_error(run):
        with pytest.raises(SystemExit) as exc:
            run()
        assert exc.value.code == 2
    
  5. 5Run the tests and the linter

    Run
    uv run pytest -v
    uv run ruff check
    

    Expected output

    collecting ... collected 5 items
    
    tests/test_cli.py::test_add_then_list PASSED                             [ 20%]
    tests/test_cli.py::test_done_hides_task_unless_all PASSED                [ 40%]
    tests/test_cli.py::test_tasks_are_saved_as_json PASSED                   [ 60%]
    tests/test_cli.py::test_unknown_task_exits_with_1 PASSED                 [ 80%]
    tests/test_cli.py::test_missing_command_is_a_usage_error PASSED          [100%]
    
    ============================== 5 passed in 0.05s ===============================
    All checks passed!
    Hint

    Ruff first reported E501 Line too long here; shortening the parser description fixed it.

  6. 6Use it during development

    TASKBOX_DB points the tool at a throwaway file, so you don't fill your home folder while testing.

    Run
    export TASKBOX_DB=$PWD/dev-tasks.json
    uv run taskbox add Buy milk
    uv run taskbox add Write the report
    uv run taskbox done 1
    uv run taskbox list
    uv run taskbox list --all
    uv run taskbox done 7; echo "exit status: $?"
    

    Expected output

    Added #1: Buy milk
    Added #2: Write the report
    Done #1: Buy milk
    [ ] #2 Write the report
    [x] #1 Buy milk
    [ ] #2 Write the report
    taskbox: no task #7
    exit status: 1
  7. 7Read the generated help

    Run
    uv run taskbox --help
    uv run taskbox --version
    

    Expected output

    usage: taskbox [-h] [--db DB] [--version] {add,list,done} ...
    
    A tiny to-do list.
    
    positional arguments:
      {add,list,done}
        add            add a task
        list           show open tasks
        done           mark a task as finished
    
    options:
      -h, --help       show this help message and exit
      --db DB          task file (default: $TASKBOX_DB or ~/.taskbox.json)
      --version        show program's version number and exit
    taskbox 0.1.0
  8. 8Build a wheel

    A wheel is the installable package format. uv build also makes a source distribution.

    Run
    uv build
    unzip -l dist/taskbox-0.1.0-py3-none-any.whl
    

    Expected output

    Building source distribution...
    Building wheel from source distribution...
    Successfully built dist/taskbox-0.1.0.tar.gz
    Successfully built dist/taskbox-0.1.0-py3-none-any.whl
    Archive:  dist/taskbox-0.1.0-py3-none-any.whl
      Length      Date    Time    Name
    ---------  ---------- -----   ----
            0  1980-01-01 00:00   taskbox/
            0  1980-01-01 00:00   taskbox/__init__.py
         2686  1980-01-01 00:00   taskbox/cli.py
            0  1980-01-01 00:00   taskbox-0.1.0.dist-info/
           81  1980-01-01 00:00   taskbox-0.1.0.dist-info/WHEEL
           46  1980-01-01 00:00   taskbox-0.1.0.dist-info/entry_points.txt
          220  1980-01-01 00:00   taskbox-0.1.0.dist-info/METADATA
          444  1980-01-01 00:00   taskbox-0.1.0.dist-info/RECORD
    ---------                     -------
         3477                     8 files
    Check:

    Only the package is inside: no tests, no .venv. The fixed 1980 dates make builds reproducible.

  9. 9Install it like any other tool

    uv tool install gives the tool its own isolated environment and puts taskbox on your PATH.

    Run
    uv tool install dist/taskbox-0.1.0-py3-none-any.whl
    taskbox add Installed from a wheel
    taskbox list
    

    Expected output

    Resolved 1 package in 1ms
    Prepared 1 package in 6ms
    Installed 1 package in 1ms
     + taskbox==0.1.0 (from file:///.../taskbox/dist/taskbox-0.1.0-py3-none-any.whl)
    Installed 1 executable: taskbox
    Added #1: Installed from a wheel
    [ ] #1 Installed from a wheel
    Check:

    which taskbox points outside the project folder. Remove it later with uv tool uninstall taskbox.

In production

Internal tools become production systems the moment other people or cron jobs depend on them.

What changes

In this lab In production
A wheel built on your laptop CI builds the wheel from a Git tag, so every release is traceable to a commit
uv tool install from a file Install from a package index: PyPI with trusted publishing, or a private index (Artifactory, CodeArtifact, Artifact Registry)
Version 0.1.0 forever Semantic versioning and a changelog; breaking a flag or an output format is a major version
A JSON file in your home folder Configuration with a clear order (flag, then environment variable, then config file, then default) and documented locations
Plain text output A --json output mode for scripts, so text can change without breaking automation
Errors as one line The same, plus --verbose for details; never a traceback for an expected error

The contract is the product

Scripts depend on your exit statuses, stdout format and flag names. The tests in this lab check exactly those, which is what lets you refactor the internals safely.

Production checklist

  • Exit status 0 on success, non-zero on failure; errors on stderr
  • Tests cover every subcommand, error path and exit status
  • Files are written atomically (temporary file, then rename)
  • Releases are built by CI from tags and published to an index
  • Versioning and a changelog tell users when behaviour changes
  • Machine-readable output for scripts (--json)

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake