Skip to main content

A rich help formatter for argparse

Project description

rich-argparse

tests pre-commit code style: black

Format argparse help output with rich.

python -m rich_argparse --help

Installation

Copy the file rich_argparse.py to your project.

Usage

Pass the formatter_class to the argument parser

import argparse
from rich_argparse import RichHelpFormatter

parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
...

Recipes

argparse's subparsers

argparse subparsers do not inherit the formatter class from the parent parser. To have the help text of subparsers formatted with rich, you have to explicitly pass formatter_class to the subparsers:

  1. you can pass it to all subparsers at once:
     subparsers = parser.add_subparsers(
         ..., parser_class=lambda **k: type(parser)(**k, formatter_class=parser.formatter_class),
     )
     p1 = subparsers.add_parser(...)
     p2 = subparsers.add_parser(...)
    
  2. or to each subparser individually:
     subparsers = parser.add_subparsers(...)
     p1 = subparsers.add_parser(..., formatter_class=parser.formatter_class)
     p2 = subparsers.add_parser(..., formatter_class=parser.formatter_class)
    

django's commands

django uses argparse for its built in commands as well as for extension libraries and user defined commands. To use rich_argparse with these commands, change your manage.py file as follows:

diff --git a/my_project/manage.py b/my_project/manage.py
index 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 os
 import sys


 def main():
     """Run administrative tasks."""
     os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')
     try:
         from django.core.management import execute_from_command_line
     except 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 RichDjangoHelpFormatter(RichHelpFormatter, DjangoHelpFormatter):  # rich 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 = RichDjangoHelpFormatter  # 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 like: python manage.py runserver --help

Special text highlighting

You can highlight patterns in the help text of your CLI. By default, RichHelpFormatter defines the following styles:

>>> pprint(RichHelpFormatter.styles)
{'argparse.args': 'italic cyan',
 'argparse.groups': 'bold italic dark_orange',
 'argparse.help': 'default',
 'argparse.syntax': '#E06C75',
 'argparse.text': 'italic'}

The following example highlights all occurrences of pyproject.toml in 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"\W(?P<pyproject>pyproject\.toml)\W")
# pass the formatter class to argparse
parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
...

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rich_argparse-0.1.0.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rich_argparse-0.1.0-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

Details for the file rich_argparse-0.1.0.tar.gz.

File metadata

  • Download URL: rich_argparse-0.1.0.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.13

File hashes

Hashes for rich_argparse-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4cbacbc2e720d5619369fad5fa548977d8bbfd2c3875c74de2535e95c3489f6c
MD5 2ae216cbdd0b20c9a50b3cb28f62b1c2
BLAKE2b-256 163f2ff040f32823c8e686a04b39dedaf53acdc02b4acdbe20449633cac03dc2

See more details on using hashes here.

File details

Details for the file rich_argparse-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: rich_argparse-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.13

File hashes

Hashes for rich_argparse-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 72c9dd6504cf8f58a479079c1dc9409cc2f5ae06bfa9e3811885340d198f9187
MD5 4fad7cdb9b8ca132966bbdcc5ab2c0a3
BLAKE2b-256 234eb73aaa1cb59cfc5729c721db2b9b6f1979ee29a038fe324ea3329df3efc7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page