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.
Python code
27 linesimport 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
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
- Use argparse's built-in help formatting for automatic flag alignment and wrapping
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.