Format click help output nicely with rich
—
Enhanced Click classes with rich formatting capabilities. These classes extend Click's core functionality to provide rich text formatting, enhanced help output, and improved visual presentation for command-line applications.
Enhanced Click command class with Rich formatting capabilities for help output and error messages.
class RichCommand(click.Command):
"""
Richly formatted click Command.
Inherits click.Command and overrides help and error methods
to print richly formatted output.
Attributes:
- context_class: Type[RichContext] = RichContext
- _formatter: Optional[RichHelpFormatter] = None
"""
def __init__(self, *args, **kwargs):
"""Create Rich Command instance."""
@property
def console(self) -> Optional["Console"]:
"""
Rich Console instance.
This is a separate instance from the help formatter that allows
full control of the console configuration.
"""
@property
def help_config(self) -> Optional[RichHelpConfiguration]:
"""Rich Help Configuration (deprecated)."""Usage example:
import rich_click as click
# Using RichCommand directly
cmd = click.RichCommand(
name="hello",
callback=lambda: click.echo("Hello!"),
help="A hello command"
)
# Using via decorator (recommended)
@click.command(cls=click.RichCommand)
def hello():
"""A hello command."""
click.echo("Hello!")Enhanced Click group class with Rich formatting capabilities for multi-command applications.
class RichGroup(click.Group):
"""
Richly formatted click Group.
Inherits click.Group and provides rich formatting for
command groups and subcommands.
"""Usage example:
import rich_click as click
# Using RichGroup directly
@click.group(cls=click.RichGroup)
def cli():
"""My CLI application."""
pass
@cli.command()
def hello():
"""Say hello."""
click.echo("Hello!")
# Using via decorator (recommended)
@click.group() # Uses RichGroup by default
def cli():
"""My CLI application."""
passEnhanced Click command collection with Rich formatting capabilities.
class RichCommandCollection(click.CommandCollection):
"""
Richly formatted click CommandCollection.
Inherits click.CommandCollection and provides rich formatting
for collections of commands.
"""Enhanced Click context class with Rich capabilities including console access and export functionality.
class RichContext(click.Context):
"""
Click Context class endowed with Rich superpowers.
Attributes:
- formatter_class: Type[RichHelpFormatter] = RichHelpFormatter
- console: Optional["Console"] = None
- export_console_as: Literal[None, "html", "svg"] = None
- errors_in_output_format: bool = False
"""
def __init__(self, *args, rich_console=None, rich_help_config=None, **kwargs):
"""
Create Rich Context instance.
Parameters:
- *args: Args passed to click.Context
- rich_console (Console, optional): Rich Console instance
- rich_help_config (Union[Mapping, RichHelpConfiguration], optional):
Rich help configuration
- **kwargs: Kwargs passed to click.Context
"""
def make_formatter(self, error=False) -> RichHelpFormatter:
"""
Create the Rich Help Formatter.
Parameters:
- error (bool): Whether this is for error formatting
Returns:
RichHelpFormatter: Configured formatter instance
"""
def exit(self, code=0):
"""
Enhanced exit with export capabilities.
Parameters:
- code (int): Exit code, defaults to 0
If export_console_as is set, exports console output as HTML or SVG
before exiting.
"""Usage example:
import rich_click as click
from rich.console import Console
# Context is automatically created with rich capabilities
@click.command()
@click.pass_context
def hello(ctx):
"""Command using rich context."""
# ctx is automatically a RichContext
console = ctx.console or Console()
console.print("Hello from Rich!", style="bold blue")
# Manual context creation
console = Console(width=120)
ctx = click.RichContext(
command=hello,
rich_console=console,
rich_help_config={"style_option": "bold red"}
)Comprehensive configuration class for customizing Rich-Click help formatting and behavior.
class RichHelpConfiguration:
"""
Rich Help Configuration class.
When merging multiple RichHelpConfigurations together, user-defined values
always take precedence over the class's defaults.
"""
# Style configuration fields (selection of key ones)
style_option: str = "bold cyan"
style_argument: str = "bold cyan"
style_command: str = "bold cyan"
style_switch: str = "bold green"
style_metavar: str = "bold yellow"
style_usage: str = "yellow"
style_deprecated: str = "red"
style_helptext: str = "dim"
# Panel and table styling
style_options_panel_border: str = "dim"
style_options_panel_box: Optional[str] = "ROUNDED"
style_commands_panel_border: str = "dim"
style_errors_panel_border: str = "red"
# Terminal configuration
width: Optional[int] = None
max_width: Optional[int] = None
color_system: Optional[str] = "auto"
force_terminal: Optional[bool] = None
# Text configuration
header_text: Optional[str] = None
footer_text: Optional[str] = None
deprecated_string: str = "(Deprecated) "
default_string: str = "[default: {}]"
arguments_panel_title: str = "Arguments"
options_panel_title: str = "Options"
commands_panel_title: str = "Commands"
# Behavior configuration
show_arguments: bool = False
show_metavars_column: bool = True
append_metavars_help: bool = False
group_arguments_options: bool = False
text_markup: str = "ansi"
use_markdown: bool = False
use_rich_markup: bool = False
command_groups: Dict[str, List[CommandGroupDict]] = field(default_factory=dict)
option_groups: Dict[str, List[OptionGroupDict]] = field(default_factory=dict)
@classmethod
def load_from_globals(cls, module=None, **extra):
"""
Build a RichHelpConfiguration from globals in rich_click.rich_click.
Parameters:
- module (ModuleType, optional): Module to load from
- **extra: Additional configuration overrides
Returns:
RichHelpConfiguration: Configuration instance
"""
def dump_to_globals(self, module=None):
"""
Dump configuration to module globals.
Parameters:
- module (ModuleType, optional): Module to dump to
"""Usage example:
import rich_click as click
# Create configuration
config = click.RichHelpConfiguration(
style_option="bold red",
style_command="bold blue",
show_arguments=True,
options_panel_title="Available Options",
commands_panel_title="Available Commands"
)
# Use with decorator
@click.command()
@click.rich_config(config)
def hello():
"""Configured command."""
click.echo("Hello!")
# Load from globals
config = click.RichHelpConfiguration.load_from_globals()
# Modify and dump back
config.style_option = "bold yellow"
config.dump_to_globals()Deprecated class, use RichGroup instead.
class RichMultiCommand:
"""
Deprecated class. Use RichGroup instead.
This class is deprecated and will be removed in Click 9.0.
Use RichGroup for multi-command functionality.
"""# Type definitions for configuration
CommandGroupDict = TypedDict('CommandGroupDict', {
'name': NotRequired[str],
'commands': List[str],
'table_styles': NotRequired[Dict[str, Any]],
'panel_styles': NotRequired[Dict[str, Any]],
'deduplicate': NotRequired[bool]
})
OptionGroupDict = TypedDict('OptionGroupDict', {
'name': NotRequired[str],
'options': NotRequired[List[str]],
'table_styles': NotRequired[Dict[str, Any]],
'panel_styles': NotRequired[Dict[str, Any]],
'deduplicate': NotRequired[bool]
})Install with Tessl CLI
npx tessl i tessl/pypi-rich-click