Python CLI Applications — argparse, click, and Typer
In this tutorial, you will learn about Python CLI Applications. We cover key concepts, practical examples, and best practices to help you master this topic.
Command-line interfaces (CLIs) are how developers interact with tools. Python makes building CLIs easy with three main approaches: argparse (standard library), click (decorator-based), and Typer (modern type-hinted).
In this tutorial, you'll learn all three. DodaTech builds CLI tools for system administrators to run security scans, analyze logs, and manage configurations.
What You'll Learn
- argparse: positional args, optional args, flags, subcommands
- click: decorators, groups, prompts, colors
- Typer: type hints, auto-generated help, shell completion
- Exit codes, error handling, and logging
argparse — Standard Library
import argparse
parser = argparse.ArgumentParser(description="Search log files")
parser.add_argument("pattern", help="Pattern to search for")
parser.add_argument("file", nargs="+", help="File(s) to search")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
parser.add_argument("--max-results", type=int, default=10, help="Max results")
parser.add_argument("--format", choices=["text", "json"], default="text")
args = parser.parse_args()
# Use arguments
print(f"Searching for '{args.pattern}' in {len(args.file)} files")
if args.verbose:
print(f"Verbose mode enabled")
click — Decorator-Based
import click
@click.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("-o", "--output", default="output.txt", help="Output file")
@click.option("--verbose", is_flag=True, help="Verbose mode")
@click.option("--limit", default=100, type=int, help="Line limit")
def process(input_file, output, verbose, limit):
"""Process a file and save results."""
click.echo(f"Processing {input_file}")
if verbose:
click.echo(f"Output: {output}, Limit: {limit}")
# Process file...
# Run: python script.py input.txt -o result.txt --verbose
Typer — Modern Type-Hinted
import typer
app = typer.Typer()
@app.command()
def scan(target: str, ports: str = "80,443", verbose: bool = False):
"""Scan a target for open ports."""
if verbose:
typer.echo(f"Scanning {target} on ports {ports}")
# Scan logic...
@app.command()
def report(output: str = "report.json"):
"""Generate a scan report."""
typer.echo(f"Generating report at {output}")
if __name__ == "__main__":
app()
Practice Questions
Build a CLI tool that counts lines, words, and characters in a file.
Build a CLI tool that searches for a pattern in files and highlights matches.
Add --json and --csv output formats to a CLI tool.
Build a CLI with subcommands: init, add, list, remove (like git).
Create a CLI wrapper around an API (e.g., weather lookup).
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro