Package: rich-argparse
rich-argparseFormat argparse and optparse help usingrich.rich-argparseimproves the look and readability of argparse's help while requiring minimal
changes to the code.Table of contentsInstallationUsageOutput stylesColorsGroup namesHighlighting patterns"usage"--versionRich renderablesSubparsersDocumenting your CLIThird party formatters(ft. django)Optparse(experimental)Legacy WindowsInstallationInstall from PyPI with pip or your favorite tool.pipinstallrich-argparseUsageSimply passformatter_classto the argument parserimportargparsefromrich_argparseimportRichHelpFormatterparser=argparse.ArgumentParser(...,formatter_class=RichHelpFormatter)...rich-argparsedefines equivalents to argparse'sbuilt-in formatters:rich_argparseformatterequivalent inargparseRichHelpFormatterHelpFormatterRawDescriptionRichHelpFormatterRawDescriptionHelpFormatterRawTextRichHelpFormatterRawTextHelpFormatterArgumentDefaultsRichHelpFormatterArgumentDefaultsHelpFormatterMetavarTypeRichHelpFormatterMetavarTypeHelpFormatterOutput stylesThe default styles used byrich-argparseare carefully chosen to work in different light and dark
themes.Customize the colorsYou can customize the colors in the output by modifying thestylesdictionary on the formatter
class.rich-argparsedefines the following styles:{'argparse.args':'cyan',# for positional-arguments and --options (e.g "--help")'argparse.groups':'dark_orange',# for group names (e.g. "positional arguments")'argparse.help':'default',# for argument's help text (e.g. "show this help message and exit")'argparse.metavar':'dark_cyan',# for metavariables (e.g. "FILE" in "--file FILE")'argparse.prog':'grey50',# for %(prog)s in the usage (e.g. "foo" in "Usage: foo [options]")'argparse.syntax':'bold',# for highlights of back-tick quoted text (e.g. "`some text`")'argparse.text':'default',# for descriptions, epilog, and --version (e.g. "A program to foo")'argparse.default':'italic',# for %(default)s in the help (e.g. "Value" in "(default: Value)")}For example, to make the description and epilogitalic, change theargparse.textstyle:RichHelpFormatter.styles["argparse.text"]="italic"Customize the group name formatYou can change how the names of the groups (like'positional arguments'and'options') are
formatted by setting theRichHelpFormatter.group_name_formatterwhich is set tostr.titleby
default. Any callable that takes the group name as an input and returns a str works:RichHelpFormatter.group_name_formatter=str.upper# Make group names UPPERCASESpecial text highlightingYou canhighlight patternsin the
arguments help and the description and epilog using regular expressions. By default,rich-argparsehighlights patterns of--options-with-hyphensusing theargparse.argsstyle
and patterns of`back tick quoted text`using theargparse.syntaxstyle. You can control
what patterns are highlighted by modifying theRichHelpFormatter.highlightslist. To disable all
highlights, you can clear this list usingRichHelpFormatter.highlights.clear().You can also add custom highlight patterns and styles. The following example highlights all
occurrences ofpyproject.tomlin green:# Add a style called `pyproject` which applies a green style (any rich style works)RichHelpFormatter.styles["argparse.pyproject"]="green"# Add the highlight regex (the regex group name must match an existing style name)RichHelpFormatter.highlights.append(r"\b(?P<pyproject>pyproject\.toml)\b")# Pass the formatter class to argparseparser=argparse.ArgumentParser(...,formatter_class=RichHelpFormatter)...Colors in theusageThe usagegenerated by the formatteris colored using theargparse.argsandargparse.metavarstyles. If you use a customusagemessage in the parser, it will treated as "plain text" and willnotbe colored by default. You can enable colors in user defined usage message throughconsole markupby settingRichHelpFormatter.usage_markup = True. If you enable this option, make sure toescapeany square brackets in the usage text.Colors in--versionIf you use the"version"action from argparse, you can use console markup in theversionstring:parser.add_argument("--version",action="version",version="[argparse.prog]%(prog)s[/] version [i]1.0.0[/]")Note that theargparse.textstyle is applied to theversionstring similar to the description
and epilog.Rich descriptions and epilogYou can use any rich renderable in the descriptions and epilog. This includes all built-in rich
renderables likeTableandMarkdownand any custom renderables defined using theConsole Protcol.importargparsefromrich.markdownimportMarkdownfromrich_argparseimportRichHelpFormatterdescription="""# My programThis is a markdown description of my program.* It has a list* And a table| Column 1 | Column 2 || -------- | -------- || Value 1  | Value 2  |"""parser=argparse.ArgumentParser(description=Markdown(description,style="argparse.text"),formatter_class=RichHelpFormatter,)...Certain features aredisabledfor arbitrary renderables other than strings, including:Syntax highlighting withRichHelpFormatter.highlightsStyling with the"argparse.text"style defined inRichHelpFormatter.stylesReplacement of%(prog)swith the program nameArbitrary renderables are displayed "as is" except for long runs of empty lines that get truncated
to two empty lines following the behavior of argparse.Working with subparsersSubparsers do not inherit the formatter class from the parent parser by default. You have to pass
the formatter class explicitly:subparsers=parser.add_subparsers(...)p1=subparsers.add_parser(...,formatter_class=parser.formatter_class)p2=subparsers.add_parser(...,formatter_class=parser.formatter_class)Generate help previewYou can generate a preview of the help message for your CLI in SVG, HTML, or TXT formats using theHelpPreviewActionaction. This is useful for including the help message in the documentation of
your app. The action uses therich exporting APIinternally.importargparsefromrich.terminal_themeimportDIMMED_MONOKAIfromrich_argparseimportHelpPreviewAction,RichHelpFormatterparser=argparse.ArgumentParser(...,formatter_class=RichHelpFormatter)...parser.add_argument("--generate-help-preview",action=HelpPreviewAction,path="help-preview.svg",# (optional) or "help-preview.html" or "help-preview.txt"export_kwds={"theme":DIMMED_MONOKAI},# (optional) keywords passed to console.save_... methods)This action is hidden, it won't show up in the help message or in the parsed arguments namespace.Use it like this:pythonmy_cli.py--generate-help-preview# generates help-preview.svg (default path specified above)# orpythonmy_cli.py--generate-help-previewmy-help.svg# generates my-help.svg# orCOLUMNS=120pythonmy_cli.py--generate-help-preview# force the width of the output to 120 columnsWorking with third party formattersrich-argparsecan be used with other formatters thatdo not rely on the private internalsofargparse.HelpFormatter. A popular example isdjangothat
defines a custom help formatter that is used with its built in commands as well as with extension
libraries and user defined commands. To userich-argparsein your django project, change yourmanage.pyfile as follows:diff --git a/my_project/manage.py b/my_project/manage.pyindex 7fb6855..5e5d48a 100755--- a/my_project/manage.py+++ b/my_project/manage.py@@ -1,22 +1,38 @@#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""import osimport sysdef main():"""Run administrative tasks."""os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')try:from django.core.management import execute_from_command_lineexcept ImportError as exc:raise ImportError("Couldn't import Django. Are you sure it's installed and ""available on your PYTHONPATH environment variable? Did you ""forget to activate a virtual environment?") from exc++    from django.core.management.base import BaseCommand, DjangoHelpFormatter+    from rich_argparse import RichHelpFormatter++    class DjangoRichHelpFormatter(DjangoHelpFormatter, RichHelpFormatter):  # django first+        """A rich-based help formatter for django commands."""++    original_create_parser = BaseCommand.create_parser++    def create_parser(*args, **kwargs):+        parser = original_create_parser(*args, **kwargs)+        parser.formatter_class = DjangoRichHelpFormatter  # set the formatter_class+        return parser++    BaseCommand.create_parser = create_parser+execute_from_command_line(sys.argv)if __name__ == '__main__':main()Now try out some command likepython manage.py runserver --helpand notice how the special
ordering of the arguments applied by django is respected by the new help formatter.Optparse supportrich-argparsenow ships with experimental support foroptparse.Import optparse help formatters fromrich_argparse.optparse:importoptparsefromrich_argparse.optparseimportIndentedRichHelpFormatter# or TitledRichHelpFormatterparser=optparse.OptionParser(formatter=IndentedRichHelpFormatter())...You can also generated a more helpful usage message by passingusage=GENERATE_USAGEto the
parser. This is similar to the default behavior ofargparse.fromrich_argparse.optparseimportGENERATE_USAGE,IndentedRichHelpFormatterparser=optparse.OptionParser(usage=GENERATE_USAGE,formatter=IndentedRichHelpFormatter())Similar toargparse, you can customize the styles used by the formatter by modifying theRichHelpFormatter.stylesdictionary. These are the same styles used byargparsebut with
theoptparse.prefix instead:RichHelpFormatter.styles["optparse.metavar"]="bold magenta"Syntax highlighting works the same as withargparse.Colors in theusageare only supported when usingGENERATE_USAGE.Customizing the group name format is not supported. optparse uses Title Case format by default.Legacy Windows supportIf your application still runs on legacy Windows versions (older than Windows 10), you'll need to
enable ANSI escape sequences by callingcolorama.init()otherwise colors will be disabled:importargparseimportcoloramafromrich_argparseimportRichHelpFormattercolorama.init()parser=argparse.ArgumentParser(...,formatter_class=RichHelpFormatter)...This isnotrequired on Windows 10 and newer or on other operating systems.