Skip to main content

Programming languages · Intermediate · 22 min

Build a command-line tool in Python with argparse

By Padding · Updated 18 Nov 2026
Python 3.15.2 (python:3.15-slim) · uv 0.13

You will have logsum, a standard-library Python 3.15 command that summarises an access log, with subcommands, checked arguments, JSON or table output, proper exit codes, pytest tests, and an install through uv tool install.

On this page

Most useful scripts start as a file you run with python script.py and a few hard-coded paths. Turning one into a proper command means it takes arguments, explains itself with --help, refuses bad input with a clear message, and tells the shell whether it worked through its exit code. Python's standard library has everything for that in argparse, so the tool needs no dependencies at all.

You will build logsum, a command that reads a web server access log (the common log format Nginx and Apache write) and summarises it. It has two subcommands, paths and status, reads a file or standard input, prints a table or JSON, and is installed as a real command on your PATH. Along the way you write it as a main(argv) function, which is what makes it easy to test.

A practical reason to have a tool like this: access logs on a busy server run to hundreds of megabytes. Summarising them on the server and copying back only the result costs a few kilobytes, which matters if you work over a metered or prepaid mobile connection. logsum reads the log one line at a time and keeps only a running count for each path and status pair, so its memory use depends on how many distinct pages the site has, not on how long the log is.

Step 1 · Create a packaged project and a sample log

A command you can install needs to be a package, not a loose script. uv init --package creates one with a src/ layout and an entry point already wired up:

Bash
cd ~
uv init --package --name logsum logsum-demo
cd ~/logsum-demo

Open pyproject.toml. Near the end it has a [project.scripts] table with the line logsum = "logsum:main". That line is the whole trick: when the package is installed, a small logsum program appears that imports the logsum package and calls its main function.

Now give the tool something to read. Save this sample log in the project folder. One line in the middle is damaged on purpose, as happens when a disk fills up or a log is cut mid-write:

Bash
cat > access.log <<'LOG'
203.0.113.5 - - [26/Nov/2026:09:00:01 +0000] "GET / HTTP/1.1" 200 5120
203.0.113.5 - - [26/Nov/2026:09:00:02 +0000] "GET /styles.css HTTP/1.1" 200 1840
198.51.100.7 - - [26/Nov/2026:09:01:10 +0000] "GET / HTTP/1.1" 200 5120
198.51.100.7 - - [26/Nov/2026:09:01:12 +0000] "GET /pricing HTTP/1.1" 200 3302
192.0.2.44 - - [26/Nov/2026:09:02:00 +0000] "GET /pricing HTTP/1.1" 200 3302
192.0.2.44 - - [26/Nov/2026:09:02:05 +0000] "POST /signup HTTP/1.1" 302 0
192.0.2.44 - - [26/Nov/2026:09:02:06 +0000] "GET /welcome HTTP/1.1" 200 2210
this line was cut off when the disk filled up
203.0.113.9 - - [26/Nov/2026:09:03:30 +0000] "GET /old-page HTTP/1.1" 404 512
203.0.113.9 - - [26/Nov/2026:09:03:31 +0000] "GET /favicon.ico HTTP/1.1" 404 512
198.51.100.20 - - [26/Nov/2026:09:04:00 +0000] "GET / HTTP/1.1" 200 5120
198.51.100.20 - - [26/Nov/2026:09:04:02 +0000] "GET /api/plans HTTP/1.1" 500 89
198.51.100.20 - - [26/Nov/2026:09:04:03 +0000] "GET /api/plans HTTP/1.1" 200 1450
LOG

The addresses come from ranges reserved for documentation, so they belong to nobody.

Check it worked

Bash
uv run logsum

uv creates the project's .venv, installs the package into it, and runs the starter command, which prints a greeting such as Hello from logsum!. That proves the entry point works before you change anything.

Step 2 · Define the arguments

Replace the starter code in src/logsum/__init__.py with the first half of the tool: the parser and the log reader. Read it through before you run anything:

Bash
cat > src/logsum/__init__.py <<'PY'
"""logsum: summarise a web server access log."""

import argparse
import contextlib
import json
import re
import sys
from collections import Counter
from importlib.metadata import version

# One line of the common log format, as written by Nginx and Apache:
# 203.0.113.5 - - [26/Nov/2026:09:00:01 +0000] "GET / HTTP/1.1" 200 5120
LINE = re.compile(
    r'\S+ \S+ \S+ \[[^\]]+\] "(?P<method>[A-Z]+) (?P<path>\S+)[^"]*" '
    r"(?P<status>\d{3}) (?:\d+|-)"
)


def positive_int(text):
    try:
        number = int(text)
    except ValueError:
        raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None
    if number < 1:
        raise argparse.ArgumentTypeError(f"must be 1 or more, got {number}")
    return number


def build_parser():
    parser = argparse.ArgumentParser(
        prog="logsum",
        description="Summarise a web server access log.",
    )
    parser.add_argument(
        "--version", action="version", version=f"%(prog)s {version('logsum')}"
    )

    # Arguments every subcommand shares live on a parent parser.
    common = argparse.ArgumentParser(add_help=False)
    common.add_argument("logfile", help="the access log to read, or - for standard input")
    output = common.add_mutually_exclusive_group()
    output.add_argument(
        "--json", dest="format", action="store_const", const="json",
        help="print JSON",
    )
    output.add_argument(
        "--table", dest="format", action="store_const", const="table",
        help="print an aligned table (the default)",
    )
    common.set_defaults(format="table")

    commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")

    paths = commands.add_parser("paths", parents=[common], help="show the most requested paths")
    paths.add_argument(
        "-n", "--top", type=positive_int, default=5,
        help="how many paths to show (default: 5)",
    )
    paths.add_argument(
        "--status", choices=["2xx", "3xx", "4xx", "5xx"],
        help="count only responses in this status class",
    )

    commands.add_parser("status", parents=[common], help="count requests per status code")
    return parser


def read_requests(stream):
    """Count each (path, status) pair, and the lines that did not parse."""
    requests, skipped = Counter(), 0
    for line in stream:
        match = LINE.match(line)
        if match:
            requests[(match["path"], int(match["status"]))] += 1
        elif line.strip():
            skipped += 1
    return requests, skipped
PY

Each piece of the parser does one job:

  • logfile is a positional argument: it has no dashes, it is required, and its meaning comes from its position.
  • --top is an optional argument with a short form, -n. Its type is a function. argparse passes it the raw text and stores whatever it returns, so --top 3 arrives as the integer 3. When the function raises ArgumentTypeError, argparse turns the message into a usage error. A plain type=int would accept -4, which makes no sense here.
  • --status uses choices, so anything outside the four status classes is rejected before your code runs.
  • --json and --table sit in a mutually exclusive group. Both write to the same destination, format, and argparse refuses a command line that uses both.
  • add_subparsers turns paths and status into subcommands, each with its own options and help. required=True makes a bare logsum an error rather than a silent no-op.
  • The common parser holds what both subcommands share. Passing it as parents=[common] copies its arguments and defaults into each one, so logfile, --json and --table are defined once.
  • The version action reads the version from the installed package metadata, which comes from pyproject.toml, so it never drifts from the release number.

read_requests does not keep the lines it reads. It adds one to a Counter keyed by (path, status), so a log of a million requests to fifty pages holds at most a few hundred entries in memory.

Check it worked

Ask the parser what it makes of a command line, without running the rest of the tool:

Bash
uv run python -c "from logsum import build_parser; print(build_parser().parse_args(['paths', 'access.log', '-n', '3', '--json']))"

The output is a Namespace with command='paths', logfile='access.log', format='json', status=None and top=3. The 3 has no quotes: the type function has already converted it.

Step 3 · Write main and produce output

Add the second half to the same file. cat >> appends, so the parser code stays as it is:

Bash
cat >> src/logsum/__init__.py <<'PY'


def open_log(name):
    if name == "-":
        return contextlib.nullcontext(sys.stdin)
    return open(name, encoding="utf-8", errors="replace")


def count_paths(requests, top, status_class):
    wanted = int(status_class[0]) if status_class else None
    counts = Counter()
    for (path, status), n in requests.items():
        if wanted is None or status // 100 == wanted:
            counts[path] += n
    return [{"path": p, "requests": n} for p, n in counts.most_common(top)]


def count_statuses(requests):
    counts = Counter()
    for (_, status), n in requests.items():
        counts[status] += n
    return [{"status": s, "requests": counts[s]} for s in sorted(counts)]


def print_table(rows):
    if not rows:
        print("no matching requests")
        return
    label, count = rows[0].keys()
    width = max(len(label), *(len(str(row[label])) for row in rows))
    print(f"{label.upper():<{width}}  {count.upper():>8}")
    for row in rows:
        print(f"{row[label]!s:<{width}}  {row[count]:>8}")


def main(argv=None):
    args = build_parser().parse_args(argv)
    try:
        with open_log(args.logfile) as stream:
            requests, skipped = read_requests(stream)
    except OSError as err:
        print(f"logsum: error: cannot read {args.logfile}: {err.strerror}", file=sys.stderr)
        return 1

    if skipped:
        print(f"logsum: warning: skipped {skipped} line(s) not in common log format", file=sys.stderr)
    if not requests:
        print("logsum: error: no requests found in the log", file=sys.stderr)
        return 1

    if args.command == "paths":
        rows = count_paths(requests, args.top, args.status)
    else:
        rows = count_statuses(requests)

    if args.format == "json":
        print(json.dumps(rows, indent=2))
    else:
        print_table(rows)
    return 0
PY

Two design choices matter here. main takes an optional argv list. The installed command calls main() with nothing, so argparse reads sys.argv; a test calls main(["paths", "x.log"]) with exactly the arguments it wants. And main returns an exit code instead of calling sys.exit itself. The logsum program that uv generates from [project.scripts] passes the return value to sys.exit, so 0 reaches the shell as success.

The file is opened after parsing, inside a with block, so it is always closed. argparse has a FileType helper that opens files during parsing, but the Python documentation has marked it deprecated since 3.14, partly because a later bad argument can leave the file open.

Try both subcommands:

Bash
uv run logsum paths access.log --top 3
uv run logsum status access.log
uv run logsum paths access.log --status 4xx --json

Check it worked

Each run starts with logsum: warning: skipped 1 line(s) not in common log format, for the damaged line. The first then prints a table headed PATH and REQUESTS with / on 3, /pricing on 2 and /api/plans on 2. The second lists status codes 200 (8 requests), 302 (1), 404 (2) and 500 (1). The third prints a JSON list with /old-page and /favicon.ico, one request each.

Step 4 · Let argparse reject bad input

You wrote no error handling for the arguments, yet the tool already has it. Try four mistakes. Each || echo shows the exit status and keeps your shell session going:

Bash
uv run logsum paths access.log --top 0 || echo "exit status $?"
uv run logsum paths access.log --status 6xx || echo "exit status $?"
uv run logsum paths access.log --json --table || echo "exit status $?"
uv run logsum || echo "exit status $?"

Then look at the help argparse wrote for you, and the version:

Bash
uv run logsum --help
uv run logsum paths --help
uv run logsum --version

Check it worked

Every mistake prints a short usage line and one error, then exit status 2. The messages say must be 1 or more, got 0, name the four allowed choices, say --table is not allowed with argument --json, and say the COMMAND argument is required. --help lists paths and status with their one-line descriptions, paths --help shows -n, --top TOP and the status choices, and --version prints logsum 0.1.0. From Python 3.15, argparse also suggests the nearest match when you mistype a choice or subcommand.

Step 5 · Read standard input and use exit codes

Unix tools chain together because they read standard input and report failure through their exit code. logsum follows three conventions:

  • 0 means it worked.
  • 1 means the arguments were fine but the job failed, such as a missing file or a log with nothing usable in it.
  • 2 means the command line itself was wrong. argparse uses this for every usage error, and your own code should leave it to argparse.

Messages go to stderr and results go to stdout, so a pipe or a redirect carries only the results. Pass - as the file name to read from a pipe:

Bash
grep ' 404 ' access.log | uv run logsum status - --json
uv run logsum paths missing.log || echo "exit status $?"
uv run logsum paths missing.log 2>/dev/null || echo "exit status $?"
echo "not a log line" | uv run logsum status - || echo "exit status $?"

The same pattern works on a server with rotated, compressed logs, without unpacking them to disk: zcat /var/log/nginx/access.log.2.gz | logsum paths -.

Check it worked

The first command prints a JSON list with one entry, status 404 with 2 requests, and no warning, because grep dropped the damaged line. The second prints logsum: error: cannot read missing.log: No such file or directory and exit status 1. The third prints only exit status 1: the error went to stderr, which 2>/dev/null discarded. The fourth warns about the skipped line, reports no requests found in the log, and exits with 1.

Step 6 · Test the command with pytest

Because main takes a list and returns a number, a test can call it like any other function. pytest's capsys fixture captures what it prints, tmp_path gives each test its own folder, and monkeypatch swaps standard input. Add pytest as a development dependency and write the tests:

Bash
uv add --dev "pytest>=9.2,<9.3"
mkdir -p tests
cat > tests/test_cli.py <<'PY'
import io
import json
import sys

import pytest

from logsum import main

LOG = """\
198.51.100.7 - - [26/Nov/2026:09:01:10 +0000] "GET / HTTP/1.1" 200 5120
198.51.100.7 - - [26/Nov/2026:09:01:12 +0000] "GET /pricing HTTP/1.1" 200 3302
192.0.2.44 - - [26/Nov/2026:09:02:00 +0000] "GET / HTTP/1.1" 404 512
"""


@pytest.fixture
def log_file(tmp_path):
    path = tmp_path / "access.log"
    path.write_text(LOG, encoding="utf-8")
    return path


def test_paths_as_json(log_file, capsys):
    assert main(["paths", str(log_file), "--json"]) == 0
    rows = json.loads(capsys.readouterr().out)
    assert rows[0] == {"path": "/", "requests": 2}


def test_status_class_filter(log_file, capsys):
    assert main(["paths", str(log_file), "--status", "4xx", "--json"]) == 0
    assert json.loads(capsys.readouterr().out) == [{"path": "/", "requests": 1}]


def test_reads_standard_input(monkeypatch, capsys):
    monkeypatch.setattr(sys, "stdin", io.StringIO(LOG))
    assert main(["status", "-", "--json"]) == 0
    assert [row["status"] for row in json.loads(capsys.readouterr().out)] == [200, 404]


def test_missing_file_exits_with_1(tmp_path, capsys):
    assert main(["status", str(tmp_path / "nope.log")]) == 1
    captured = capsys.readouterr()
    assert captured.out == ""
    assert "cannot read" in captured.err


@pytest.mark.parametrize(
    "extra",
    [["--top", "0"], ["--top", "many"], ["--status", "6xx"], ["--json", "--table"]],
)
def test_bad_arguments_exit_with_2(log_file, capsys, extra):
    with pytest.raises(SystemExit) as stopped:
        main(["paths", str(log_file), *extra])
    assert stopped.value.code == 2
    assert "error" in capsys.readouterr().err
PY
uv run pytest

argparse stops a bad command line by raising SystemExit, which is why the last test uses pytest.raises: the test sees the exit code without ending the test run. pytest finds the logsum package because uv installed the project into its environment.

Check it worked

The summary line reads 8 passed: four single tests plus four rows of the parametrised one. To see a test catch a regression, change the return 1 after cannot read to return 0 and run uv run pytest again: test_missing_file_exits_with_1 fails. Put it back before you go on.

Step 7 · Install it as a command

uv run only works inside the project. To use logsum from any folder, install it as a tool. uv builds the package, gives it an isolated environment of its own, and puts the logsum program in its tool directory, usually ~/.local/bin:

Bash
uv tool install .

If uv warns that this directory is not on your PATH, let it add the directory to your shell's start-up file, then open a new terminal:

Bash
uv tool update-shell

Now run it from somewhere else, the way you would on a server:

Bash
cd ~
logsum --version
logsum status ~/logsum-demo/access.log --json
cat ~/logsum-demo/access.log | logsum paths - -n 2

The installed copy is a snapshot. After you change the code, run uv tool install --reinstall . from the project folder, or install with uv tool install --editable . while you are still developing, so the command always runs your latest source.

Check it worked

logsum --version prints logsum 0.1.0 from your home folder, with no uv run in front. which logsum shows a path inside uv's tool directory, and uv tool list shows something like logsum v0.1.0 with its logsum command.

Step 8 · Compare the same interface in Typer

argparse is in every Python installation, which is why it suits tools that must run on any server without installing anything. Typer is the common alternative: you write ordinary functions with type hints, and it builds the parser, help and validation from them. It is one package to add, and it brings a few libraries of its own, such as Rich for formatted help and errors.

Here is the interface of logsum sketched in Typer, without the log reading. Save it beside the project, then run it with Typer added just for that run, so the real project stays dependency-free:

Bash
cd ~/logsum-demo
cat > typer_sketch.py <<'PY'
from enum import Enum
from typing import Annotated

import typer

app = typer.Typer(help="Summarise a web server access log.")


class StatusClass(str, Enum):
    success = "2xx"
    redirect = "3xx"
    client_error = "4xx"
    server_error = "5xx"


class Format(str, Enum):
    table = "table"
    json = "json"


@app.command()
def paths(
    logfile: Annotated[str, typer.Argument(help="The access log, or - for standard input.")],
    top: Annotated[int, typer.Option("--top", "-n", min=1, help="How many paths to show.")] = 5,
    status_class: Annotated[StatusClass | None, typer.Option("--status")] = None,
    output: Annotated[Format, typer.Option("--format")] = Format.table,
):
    """Show the most requested paths."""
    picked = status_class.value if status_class else "all"
    typer.echo(f"paths in {logfile}: top {top}, status {picked}, format {output.value}")


@app.command()
def status(
    logfile: str,
    output: Annotated[Format, typer.Option("--format")] = Format.table,
):
    """Count requests per status code."""
    typer.echo(f"status in {logfile}: format {output.value}")


if __name__ == "__main__":
    app()
PY
uv run --with "typer>=0.29,<0.30" typer_sketch.py paths access.log -n 3 --status 4xx
uv run --with "typer>=0.29,<0.30" typer_sketch.py paths access.log --top 0 || echo "exit status $?"

The type hints do the work of type=, choices= and help=: int with min=1 replaces positive_int, and the Enum replaces the choices list. Two differences matter when you choose. Typer has no direct equivalent of add_mutually_exclusive_group, so the sketch uses a single --format option with choices instead of --json and --table. And Typer is a dependency you install, pin and update, where argparse ships with Python. A good rule: argparse for small tools and scripts that must run anywhere, Typer for larger CLIs with many commands where the shorter code pays for the dependency.

Check it worked

The first run prints paths in access.log: top 3, status 4xx, format table. The second prints a formatted error saying 0 is out of range for --top, and exit status 2, the same convention argparse follows.

Step 9 · Clean up

Remove the installed command first, then the demo project. Python and uv stay installed:

Bash
uv tool uninstall logsum
cd ~
rm -rf ~/logsum-demo

Check it worked

uv tool list no longer has a logsum line, and ls "$(uv tool dir --bin)" no longer shows a logsum file. If you check with command -v logsum in the same bash session, run hash -r first: bash remembers where it last found a command and can still print the old path after the file is gone.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.