Build Command Line Tools with argparse, Click, and Rich - Python CLI Tutorial #37
Video: Build Command Line Tools with argparse, Click, and Rich - Python CLI Tutorial #37 by Taught by Celeste AI - AI Coding Coach
Watch full page →Build Command Line Tools with argparse, Click, and Rich - Python CLI Tutorial
Creating professional command line interfaces (CLI) in Python is straightforward with libraries like argparse, Click, and Rich. This guide demonstrates how to parse arguments, build commands, and enhance output formatting to create user-friendly CLI applications.
Code
import argparse
import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
# argparse example: basic argument parsing
def argparse_example():
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_true',
help='sum the integers (default: find the max)')
args = parser.parse_args()
if args.accumulate:
print(f"Sum: {sum(args.integers)}")
else:
print(f"Max: {max(args.integers)}")
# Click example: building commands with decorators
@click.group()
def cli():
"""Simple CLI with Click"""
pass
@cli.command()
@click.argument('name')
@click.option('--greet', is_flag=True, help="Include greeting")
def hello(name, greet):
"""Say hello to NAME"""
if greet:
click.echo(click.style(f"Hello, {name}!", fg='green', bold=True))
else:
click.echo(f"{name}")
@cli.command()
@click.option('--count', default=1, help='Number of times to repeat')
@click.option('--choice', type=click.Choice(['red', 'blue', 'green']), default='red')
def repeat(count, choice):
"""Repeat a message with color"""
for _ in range(count):
click.echo(click.style(f"This is {choice} text.", fg=choice))
# Rich example: formatted table and panel output
def rich_report():
console = Console()
table = Table(title="Sample Report")
table.add_column("Name", style="cyan", no_wrap=True)
table.add_column("Age", justify="right")
table.add_column("Score", justify="right")
data = [("Alice", 30, 12345), ("Bob", 24, 67890), ("Carol", 29, 54321)]
for name, age, score in data:
table.add_row(name, str(age), f"{score:,}")
panel = Panel(table, title="User Data", subtitle="Report generated with Rich", expand=False)
console.print(panel)
if __name__ == "__main__":
# Uncomment to test argparse example:
# argparse_example()
# Uncomment to run Click CLI:
# cli()
# Run Rich report demo:
rich_report()
Key Points
- argparse allows you to define positional and optional command-line arguments with types and flags.
- Click simplifies CLI creation using decorators for commands, options, and argument validation.
- Use click.style() to add colored and styled text output in terminal applications.
- Rich provides powerful tools to create formatted tables and panels for visually appealing CLI reports.
- Combining these libraries lets you build robust, user-friendly, and attractive command line tools in Python.