Format CLI help text in Python

Build a readable usage string for a command-line tool, aligning flags and wrapping descriptions with the textwrap module.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

27 lines
Python 3.9+
import textwrap


def format_help(command_name: str, description: str, options: list[tuple[str, str]]) -> str:
    """Format CLI help text into a readable usage string."""
    header = f"Usage: {command_name} [OPTIONS]"
    lines = [header, "", description, "", "Options:"]

    for flag, help_text in options:
        wrapped_help = textwrap.fill(
            help_text,
            width=50,
            initial_indent=" " * 4,
            subsequent_indent=" " * 8,
        )
        lines.append(f"  {flag:<10}{wrapped_help.strip()}")

    return "\n".join(lines)


if __name__ == "__main__":
    options = [
        ("-v, --verbose", "Enable verbose output for debugging"),
        ("-o, --output FILE", "Write result to the specified file"),
        ("-h, --help", "Show this help message and exit"),
    ]
    print(format_help("mycli", "A simple CLI tool for demonstration.", options))

Output

stdout
Usage: mycli [OPTIONS]

A simple CLI tool for demonstration.

Options:
  -v, --verbose  Enable verbose output for debugging
  -o, --output   FILE  Write result to the specified file
  -h, --help     Show this help message and exit

How it works

The function builds a list of lines starting with a usage header and description, then appends each option. For every flag, textwrap.fill wraps long help text to a width of 50 characters, using a 4-space initial indent and 8-space subsequent indent for hanging alignment. Left-justifying the flag with {flag:<10} ensures clean column alignment across options. Finally, the lines are joined with newlines to produce the final help string.

Common mistakes

  • Not adjusting the wrapping indent to match flag column width, causing misaligned help text
  • Forgetting to strip the wrapped text, leaving leading spaces before the help description
  • Hardcoding flags instead of passing them as tuples, making the function less reusable

Variations

  1. Use argparse's built-in help formatting for automatic flag alignment and wrapping
  2. Build the help string with f-strings and explicit padding for short, fixed-width options

Real-world use cases

  • Generating --help output for a custom CLI tool without relying on argparse's default style.
  • Producing dynamic help for a script that accepts a variable set of plugin options.
  • Creating consistent help text across multiple subcommands in a larger CLI application.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.