31. Building a CLI Tool
Command-line tools turn scripts into shareable utilities. Python's ecosystem offers several frameworks; click hits the sweet spot of simplicity and capability.
Getting started with click:
#!/usr/bin/env python3
"""CLI tool for processing AI documents."""
import click
from pathlib import Path
@click.group()
@click.version_option(version="1.0.0")
def cli():
"""AI document processing toolkit."""
pass
@cli.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("--output", "-o", type=click.Path(), help="Output file path")
@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output")
def process(input_file, output, verbose):
"""Process a document through the AI pipeline."""
if verbose:
click.echo(f"Processing: {input_file}")
with open(input_file) as f:
content = f.read()
word_count = len(content.split())
char_count = len(content)
if verbose:
click.echo(f"Words: {word_count}, Characters: {char_count}")
result = f"Document: {Path(input_file).name}\nWords: {word_count}\n"
if output:
Path(output).write_text(result)
click.echo(f"Wrote to {output}")
else:
click.echo(result)
@cli.command()
def status():
"""Check pipeline status."""
click.echo("Pipeline: Ready")
click.echo("Models: Loaded")
if __name__ == "__main__":
cli()
Run it directly: python cli_tool.py process myfile.txt -v. Or install it for command-line access. Run pip install -e . from your project root after adding to pyproject.toml:
[project.scripts]
ai-pipeline = "pipeline.cli:cli"
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Extend the CLI tool above with a new batch command that accepts a directory path and processes all .txt files within it. Add a --recursive flag. Print each filename as it's processed.