Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/optional/cli-tools/cli-tools.ipynb

View source on GitHub

Command-Line Tools#

Many scientific workflows start as scripts that you run with python my_script.py. But as your tools mature, you need proper command-line interfaces — with argument parsing, help text, and error handling. This lecture covers argparse, click, and typer, and shows how to package CLI tools as installable commands.

Section 1: Why Build CLI Tools?#

Scripts with hardcoded parameters are fragile:

# Bad: hardcoded everything
data = pd.read_csv("experiment_data.csv")
results = analyze(data, threshold=0.5, method="linear")
results.to_csv("output.csv")

Every time you want to change a parameter, you edit the source code. A CLI makes this configurable:

python analyze.py experiment_data.csv --threshold 0.5 --method linear -o output.csv

Benefits:

  • Parameters are documented via --help

  • No source code editing needed for different runs

  • Easy to script and automate (cron jobs, CI pipelines, shell scripts)

  • Reproducible — the exact command is logged in your shell history

Section 2: argparse (Standard Library)#

argparse is built into Python — no extra dependencies needed.

#!/usr/bin/env python
"""Analyze experimental data."""

import argparse
import pandas as pd

def main():
    parser = argparse.ArgumentParser(description="Analyze experimental data")
    parser.add_argument("input", help="Path to input CSV file")
    parser.add_argument("-o", "--output", default="results.csv",
                        help="Path to output file (default: results.csv)")
    parser.add_argument("-t", "--threshold", type=float, default=0.5,
                        help="Detection threshold (default: 0.5)")
    parser.add_argument("-m", "--method", choices=["linear", "polynomial", "exponential"],
                        default="linear", help="Fitting method")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Print detailed output")

    args = parser.parse_args()

    if args.verbose:
        print(f"Reading {args.input}")

    data = pd.read_csv(args.input)
    # ... analysis with args.threshold, args.method ...
    print(f"Processed {len(data)} rows, saved to {args.output}")

if __name__ == "__main__":
    main()

Usage:

python analyze.py data.csv --threshold 0.8 --method polynomial -v
python analyze.py --help

Subcommands with argparse#

For tools with multiple commands (like git commit, git push):

parser = argparse.ArgumentParser(description="Experiment manager")
subparsers = parser.add_subparsers(dest="command")

# 'run' subcommand
run_parser = subparsers.add_parser("run", help="Run an experiment")
run_parser.add_argument("config", help="Path to config file")

# 'analyze' subcommand
analyze_parser = subparsers.add_parser("analyze", help="Analyze results")
analyze_parser.add_argument("input", help="Path to results file")

args = parser.parse_args()

Section 3: click (Decorator-Based)#

click uses decorators instead of manual parser construction:

import click

@click.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("-o", "--output", default="results.csv", help="Output file path")
@click.option("-t", "--threshold", type=float, default=0.5, help="Detection threshold")
@click.option("-m", "--method", type=click.Choice(["linear", "polynomial", "exponential"]),
              default="linear", help="Fitting method")
@click.option("-v", "--verbose", is_flag=True, help="Verbose output")
def analyze(input_file, output, threshold, method, verbose):
    """Analyze experimental data from INPUT_FILE."""
    if verbose:
        click.echo(f"Reading {input_file}")
    # ... your analysis code ...
    click.echo(f"Done. Results saved to {output}")

if __name__ == "__main__":
    analyze()

click Command Groups#

@click.group()
def cli():
    """Experiment management tool."""
    pass

@cli.command()
@click.argument("config")
def run(config):
    """Run an experiment with CONFIG file."""
    click.echo(f"Running experiment with {config}")

@cli.command()
@click.argument("input_file")
def analyze(input_file):
    """Analyze results from INPUT_FILE."""
    click.echo(f"Analyzing {input_file}")

if __name__ == "__main__":
    cli()

Section 4: typer (Modern, Type-Hint Based)#

typer is built on click but uses Python type hints for even less boilerplate:

from pathlib import Path
from enum import Enum
from typing import Annotated
import typer

class Method(str, Enum):
    linear = "linear"
    polynomial = "polynomial"
    exponential = "exponential"

def analyze(
    input_file: Path,
    output: Annotated[Path, typer.Option("--output", "-o", help="Output file")] = Path("results.csv"),
    threshold: Annotated[float, typer.Option("--threshold", "-t", help="Detection threshold")] = 0.5,
    method: Annotated[Method, typer.Option("--method", "-m", help="Fitting method")] = Method.linear,
    verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Verbose output")] = False,
):
    """Analyze experimental data from INPUT_FILE."""
    if verbose:
        typer.echo(f"Reading {input_file}")
    # ... your analysis code ...
    typer.echo(f"Done. Results saved to {output}")

if __name__ == "__main__":
    typer.run(analyze)

Typer automatically generates help text from the function signature and docstring. It also provides shell completion out of the box.

Comparison#

Feature

argparse

click

typer

Standard library

Yes

No

No

Style

Imperative

Decorators

Type hints

Subcommands

Manual

@group

app.command()

Shell completion

No

Plugin

Built-in

Learning curve

Medium

Low

Low

Section 5: Entry Points in Python Packages#

Instead of running python my_script.py, you can make your tool installable as a command (e.g., analyze).

In your pyproject.toml:

[project.scripts]
analyze = "my_package.cli:main"

Where my_package/cli.py contains:

def main():
    # Your argparse/click/typer code here
    ...

After pip install -e ., you can run analyze from anywhere:

$ analyze data.csv --method polynomial --threshold 0.8

This is how tools like pytest, black, ruff, and jupyter work — they are all entry points in their respective packages.

Exercise: Convert a Script into a CLI Tool#

Start with this script that has hardcoded parameters:

import numpy as np
from scipy.optimize import curve_fit

# Hardcoded parameters
input_file = "kinetics_data.csv"
output_file = "fit_results.txt"
model_type = "first_order"  # or "second_order"

data = np.loadtxt(input_file, delimiter=",", skiprows=1)
time = data[:, 0]
concentration = data[:, 1]

def first_order(t, k, C0):
    return C0 * np.exp(-k * t)

def second_order(t, k, C0):
    return C0 / (1 + k * C0 * t)

model = first_order if model_type == "first_order" else second_order
popt, pcov = curve_fit(model, time, concentration)

with open(output_file, "w") as f:
    f.write(f"Model: {model_type}\n")
    f.write(f"Parameters: {popt}\n")

Tasks:

  1. Convert this script into a proper CLI tool using argparse, click, or typer (your choice)

  2. Add arguments for: input file, output file, model type, and a verbose flag

  3. Add --help text for every argument

  4. Add the tool as an entry point in a pyproject.toml

  5. Test it with: your-tool kinetics_data.csv -m second_order -v

Bonus: Add a --plot flag that saves a plot of the data and fit to a PNG file.

Summary#

Tool

Best For

argparse

Simple scripts, no extra dependencies

click

Medium-complexity CLIs, decorator style

typer

Modern CLIs, type-hint driven

Entry points

Making tools installable as commands

Start with argparse for quick scripts, graduate to typer for polished tools that you plan to distribute.

Tips and Tricks#

  • Prompt: “Convert this script into a CLI tool using typer”: AI handles the argparse/click/typer boilerplate very well.

  • Always include --help text: AI sometimes generates arguments without help strings — prompt: “Add help text to every argument.”

  • Use typer.echo() or click.echo() instead of print(): These handle encoding and piping correctly.

  • Prompt: “Add a --verbose flag that controls logging level”: This is a standard pattern AI generates reliably.

  • Test your CLI with subprocess.run(): subprocess.run(["python", "-m", "mypackage", "--help"]) in your test suite catches broken CLIs early.

  • Add entry points in pyproject.toml: Users should run your-tool not python -m your_package.cli — ask AI to set this up.

  • Prompt: “Add shell completion for this CLI tool”: typer and click both support this — AI knows the setup.

  • Keep subcommands shallow: tool action is better than tool group subgroup action — deep nesting confuses users.

Foundational Concepts to Commit to Memory#

  • argparse is in the standard library — no dependencies needed. It is always available and sufficient for most scripts.

  • click uses decorators, typer uses type hints — both produce cleaner code than argparse for complex CLIs, but add a dependency.

  • Every CLI argument should have help text — --help is the first thing users (including future you) will run.

  • Entry points in pyproject.toml turn your script into an installable command — pip install -e . and then run your-tool from anywhere.

  • Positional arguments are for required inputs (like file paths). Options (with --flags) are for optional configuration.

  • type=click.Path(exists=True) or argparse type checking validates inputs before your code runs — fail early, fail clearly.

  • Subcommands (like git commit, git push) organize complex tools — use argparse subparsers, click.group(), or typer app commands.

  • A CLI makes your code scriptable — other tools, cron jobs, and CI pipelines can call it without importing your Python module.

Knowing vs. Doing: Reflection#

CLI tools are one of the highest-leverage things you can build as a scientist. A script with hardcoded paths is useful to exactly one person: you, today. A script with a proper --help message and configurable arguments is useful to your entire lab, your future self, and anyone who reads your paper and wants to reproduce your results. The gap between “script” and “tool” is small in terms of code but enormous in terms of impact. And AI agents can close that gap in minutes — describe your script’s parameters and an AI will generate the argparse or typer boilerplate faster than you could type it.

But you need to know that the gap exists. If you have never seen a well-designed CLI tool, you will not think to ask an AI to build one. If you do not know what entry points are, you will keep telling collaborators to “run python /path/to/my/script.py” instead of just “run analyze.” The foundational knowledge here is not about memorizing argparse syntax — it is about knowing that CLI tools exist as a concept, that they are expected in professional software, and that Python has multiple ways to build them.

Once you know the landscape — argparse for simple things, typer for polished tools, entry points for distribution — you can let AI handle the implementation details. Your value is in deciding what the tool should do, what the interface should look like, and whether the generated code actually works with your data. Ship the tool. You will learn more from a collaborator saying “this flag does not work” than from reading another tutorial.

Additional Resources#