CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rich-argparse

Rich help formatters for argparse and optparse that enhance CLI help output with colors and formatting

Pending
Overview
Eval results
Files

django-integration.mddocs/

Django Integration

Django-specific utilities that enable rich formatting for Django management commands with project-wide configuration support. These utilities provide seamless integration with Django's command system while maintaining compatibility with existing Django commands.

Capabilities

DjangoRichHelpFormatter

A rich help formatter specifically designed for Django management commands, combining Django's DjangoHelpFormatter with rich formatting capabilities.

# From rich_argparse.django  
class DjangoRichHelpFormatter:
    """A rich help formatter for django commands."""

Usage Examples

Using with individual Django commands:

from django.core.management.base import BaseCommand
from rich_argparse.django import DjangoRichHelpFormatter

class Command(BaseCommand):
    help = "A sample Django command with rich formatting"
    
    def create_parser(self, prog_name, subcommand, **kwargs):
        parser = super().create_parser(prog_name, subcommand, **kwargs)
        parser.formatter_class = DjangoRichHelpFormatter
        return parser
    
    def add_arguments(self, parser):
        parser.add_argument("--input", help="Input file path")
        parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
    
    def handle(self, *args, **options):
        # Command implementation
        pass

Custom Django command with rich help:

from django.core.management.base import BaseCommand
from rich_argparse.django import DjangoRichHelpFormatter

class Command(BaseCommand):
    help = """
    Process user data with rich formatting support.
    
    This command demonstrates rich markup in Django command help:
    - Use `--format json` for JSON output
    - Use `--batch` for processing multiple files
    - Check the [link https://docs.djangoproject.com]Django docs[/] for more info
    """
    
    def create_parser(self, prog_name, subcommand, **kwargs):
        parser = super().create_parser(prog_name, subcommand, **kwargs)
        parser.formatter_class = DjangoRichHelpFormatter
        return parser
    
    def add_arguments(self, parser):
        parser.add_argument(
            "--format",
            choices=["json", "csv", "xml"],
            default="json",
            help="Output format for processed data"
        )
        
        parser.add_argument(
            "--batch",
            action="store_true", 
            help="Process multiple files in batch mode"
        )
        
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="""
            Perform a dry run without making changes.
            
            Useful for testing command arguments and seeing what
            would be processed without actually executing the operation.
            """
        )

richify_command_line_help

Project-wide function that sets a rich default formatter class for all Django commands, affecting built-in, third-party, and user-defined commands.

def richify_command_line_help(
    formatter_class: type[RichHelpFormatter] = DjangoRichHelpFormatter,
) -> None:
    """
    Set a rich default formatter class for BaseCommand project-wide.
    
    Calling this function affects all built-in, third-party, and user defined 
    django commands. Note that this function only changes the default formatter 
    class of commands. User commands can still override the default by explicitly 
    setting a formatter class.
    
    Args:
        formatter_class: The rich formatter class to use as default.
                        Defaults to DjangoRichHelpFormatter.
    """

Usage Examples

Enable rich formatting for all Django commands:

# In your Django project's __init__.py or apps.py
from rich_argparse.django import richify_command_line_help

# Apply rich formatting to all Django commands
richify_command_line_help()

Use custom formatter for all commands:

from rich_argparse.django import richify_command_line_help, DjangoRichHelpFormatter

# Create custom formatter class
class CustomDjangoFormatter(DjangoRichHelpFormatter):
    styles = {
        **DjangoRichHelpFormatter.styles,
        "argparse.args": "bold cyan",
        "argparse.help": "dim white"
    }

# Apply custom formatter to all Django commands
richify_command_line_help(formatter_class=CustomDjangoFormatter)

Enable in Django app configuration:

# In your app's apps.py
from django.apps import AppConfig

class MyAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'myapp'
    
    def ready(self):
        from rich_argparse.django import richify_command_line_help
        richify_command_line_help()

Complete Integration Example

Project-wide Setup

# myproject/__init__.py
from rich_argparse.django import richify_command_line_help

# Enable rich formatting for all Django commands
richify_command_line_help()

Custom Command with Rich Features

# management/commands/process_data.py
from django.core.management.base import BaseCommand, CommandError
from rich_argparse.django import DjangoRichHelpFormatter
from rich.console import Console
from rich.progress import track

class Command(BaseCommand):
    help = """
    Process application data with rich progress tracking.
    
    This command demonstrates various rich-argparse features:
    - Rich markup in help text with [bold]formatting[/bold]
    - Progress bars using `--progress` option
    - Colored output with `--color` option
    - Integration with Django's command system
    
    Examples:
        python manage.py process_data --input data.json
        python manage.py process_data --batch --progress
    """
    
    def create_parser(self, prog_name, subcommand, **kwargs):
        parser = super().create_parser(prog_name, subcommand, **kwargs)
        parser.formatter_class = DjangoRichHelpFormatter
        return parser
    
    def add_arguments(self, parser):
        parser.add_argument(
            "--input",
            type=str,
            help="""
            Input file path for data processing.
            
            Supports JSON, CSV, and XML formats. The file format
            is automatically detected based on the file extension.
            """
        )
        
        parser.add_argument(
            "--output",
            type=str,
            help="Output file path (defaults to stdout)"
        )
        
        parser.add_argument(
            "--format",
            choices=["json", "csv", "xml", "yaml"],
            default="json",
            help="Output format for processed data"
        )
        
        parser.add_argument(
            "--batch",
            action="store_true",
            help="""
            Enable batch processing mode.
            
            In batch mode, the command can process multiple input
            files and provides progress tracking for large datasets.
            """
        )
        
        parser.add_argument(
            "--progress",
            action="store_true",
            help="Show progress bar during processing"
        )
        
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="""
            Perform a dry run without making changes.
            
            Shows what would be processed without actually executing
            the data processing operations. Useful for validation.
            """
        )
    
    def handle(self, *args, **options):
        console = Console()
        
        if options["dry_run"]:
            console.print("[yellow]Dry run mode - no changes will be made[/yellow]")
        
        if options["progress"]:
            # Simulate processing with progress bar
            for i in track(range(100), description="Processing data..."):
                pass
        
        console.print("[green]Processing completed successfully![/green]")

Built-in Command Enhancement

The richify_command_line_help function automatically enhances all Django built-in commands:

# All these commands will now have rich formatting
python manage.py help          # Rich-formatted help
python manage.py runserver --help    # Rich-formatted runserver help  
python manage.py migrate --help      # Rich-formatted migrate help
python manage.py collectstatic --help  # Rich-formatted collectstatic help

Advanced Configuration

Custom Formatter Classes

from rich_argparse.django import DjangoRichHelpFormatter, richify_command_line_help
from rich_argparse import RichHelpFormatter

class CustomDjangoFormatter(DjangoRichHelpFormatter):
    """Custom Django formatter with project-specific styling."""
    
    styles = {
        **DjangoRichHelpFormatter.styles,
        "argparse.args": "bold blue",
        "argparse.groups": "bold yellow",
        "argparse.help": "bright_white",
        "argparse.metavar": "bold green"
    }
    
    # Custom group name formatting
    group_name_formatter = str.upper
    
    # Custom highlight patterns
    highlights = [
        *RichHelpFormatter.highlights,
        r"(?P<args>\bmanage\.py\b)",  # Highlight manage.py
        r"(?P<syntax>\b(?:True|False|None)\b)"  # Highlight Python literals
    ]

# Apply custom formatter project-wide
richify_command_line_help(formatter_class=CustomDjangoFormatter)

Conditional Rich Formatting

# Enable rich formatting only in development
import os
from rich_argparse.django import richify_command_line_help

if os.environ.get("DJANGO_DEBUG", "False").lower() == "true":
    richify_command_line_help()

Compatibility and Limitations

Compatibility

  • Django versions: Compatible with Django 2.2+
  • Python versions: Supports Python 3.8+
  • Command types: Works with all Django command types (BaseCommand, LabelCommand, NoArgsCommand)
  • Third-party commands: Automatically enhances third-party Django commands
  • Custom commands: Full support for custom command implementations

Limitations

  • Override behavior: Commands that explicitly set their own formatter_class will not be affected by richify_command_line_help()
  • Import requirement: Django must be installed and available for the django module to work
  • Performance: Minimal performance overhead from rich formatting

Error Handling

# Safe import with fallback
try:
    from rich_argparse.django import richify_command_line_help
    richify_command_line_help()
except ImportError:
    # Django not available or rich-argparse not installed
    pass

Install with Tessl CLI

npx tessl i tessl/pypi-rich-argparse

docs

argparse-formatters.md

contrib-formatters.md

django-integration.md

index.md

optparse-formatters.md

tile.json