Chapter 22: Building CLI Tools with argparse, Click & Typer
Learn to create powerful command-line interfaces using Python’s standard library and popular frameworks.
Downloadchapter22.py
Objectives
- Use
argparse
to parse arguments and options. - Create commands and subcommands with
Click
. - Leverage
Typer
and type hints to build CLIs. - Package your tool as a console script.
- Handle input validation, help text and error messages.
1. argparse Basics
import argparse
def main():
parser = argparse.ArgumentParser(description="Greet a user.")
parser.add_argument("name", help="Name of the user")
parser.add_argument("-t", "--times", type=int, default=1,
help="Number of greetings")
args = parser.parse_args()
for _ in range(args.times):
print(f"Hello, {args.name}!")
if __name__ == "__main__":
main()
Run: python chapter22.py Alice -t 3
2. Click
import click
@click.command()
@click.argument("name")
@click.option("--times", default=1, help="Number of greetings")
def cli(name, times):
"""Greet a user multiple times."""
for _ in range(times):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
cli()
Install: pip install click
. Run: python chapter22.py Bob --times 2
3. Typer & Type Hints
import typer
app = typer.Typer()
@app.command()
def greet(name: str, times: int = 1):
\"\"\"Greet a user multiple times.\"\"\"
for _ in range(times):
typer.echo(f"Hello, {name}!")
if __name__ == "__main__":
app()
Install: pip install typer[all]
. Run: python chapter22.py greet Carol --times 3
4. Packaging CLI Tools
Add to setup.py
or pyproject.toml
:
[project.scripts]
mycli = "mypackage.cli:app"
After installation: mycli --help
Exercises
- Extend the
argparse
example with a--uppercase
flag. - Create a Click group with two subcommands:
greet
andfarewell
. - Build a Typer app with commands to add/list/remove items from an in-memory todo list.
- Package the Typer app and install it locally as
todo-cli
.