METADATA 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. Metadata-Version: 2.4
  2. Name: rich-argparse
  3. Version: 1.7.0
  4. Summary: Rich help formatters for argparse and optparse
  5. Project-URL: Homepage, https://github.com/hamdanal/rich-argparse
  6. Project-URL: Documentation, https://github.com/hamdanal/rich-argparse#rich-argparse
  7. Project-URL: Issue-Tracker, https://github.com/hamdanal/rich-argparse/issues
  8. Project-URL: Changelog, https://github.com/hamdanal/rich-argparse/blob/main/CHANGELOG.md
  9. Author-email: Ali Hamdan <ali.hamdan.dev@gmail.com>
  10. License-Expression: MIT
  11. License-File: LICENSE
  12. Keywords: argparse,help-formatter,optparse,rich
  13. Classifier: Development Status :: 5 - Production/Stable
  14. Classifier: Environment :: Console
  15. Classifier: Intended Audience :: Developers
  16. Classifier: License :: OSI Approved :: MIT License
  17. Classifier: Operating System :: OS Independent
  18. Classifier: Programming Language :: Python :: 3.8
  19. Classifier: Programming Language :: Python :: 3.9
  20. Classifier: Programming Language :: Python :: 3.10
  21. Classifier: Programming Language :: Python :: 3.11
  22. Classifier: Programming Language :: Python :: 3.12
  23. Classifier: Programming Language :: Python :: 3.13
  24. Classifier: Programming Language :: Python :: 3.14
  25. Classifier: Topic :: Software Development :: User Interfaces
  26. Requires-Python: >=3.8
  27. Requires-Dist: rich>=11.0.0
  28. Description-Content-Type: text/markdown
  29. # rich-argparse
  30. ![python -m rich_argparse](
  31. https://github.com/hamdanal/rich-argparse/assets/93259987/5eb719ce-9865-4654-a5c6-04950a86d40d)
  32. [![tests](https://github.com/hamdanal/rich-argparse/actions/workflows/tests.yml/badge.svg)
  33. ](https://github.com/hamdanal/rich-argparse/actions/workflows/tests.yml)
  34. [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/hamdanal/rich-argparse/main.svg)
  35. ](https://results.pre-commit.ci/latest/github/hamdanal/rich-argparse/main)
  36. [![Downloads](https://img.shields.io/pypi/dm/rich-argparse)](https://pypistats.org/packages/rich-argparse)
  37. [![Python Version](https://img.shields.io/pypi/pyversions/rich-argparse)
  38. ![Release](https://img.shields.io/pypi/v/rich-argparse)
  39. ](https://pypi.org/project/rich-argparse/)
  40. Format argparse and optparse help using [rich](https://pypi.org/project/rich).
  41. *rich-argparse* improves the look and readability of argparse's help while requiring minimal
  42. changes to the code.
  43. ## Table of contents
  44. * [Installation](#installation)
  45. * [Usage](#usage)
  46. * [Output styles](#output-styles)
  47. * [Customizing colors](#customize-the-colors)
  48. * [Group name formatting](#customize-the-group-name-format)
  49. * [Special text highlighting](#special-text-highlighting)
  50. * [Customizing `usage`](#colors-in-the-usage)
  51. * [Console markup](#disable-console-markup)
  52. * [Colors in `--version`](#colors-in---version)
  53. * [Rich renderables](#rich-descriptions-and-epilog)
  54. * [Working with subparsers](#working-with-subparsers)
  55. * [Documenting your CLI](#generate-help-preview)
  56. * [Additional formatters](#additional-formatters)
  57. * [Django support](#django-support)
  58. * [Optparse support](#optparse-support) (experimental)
  59. * [Legacy Windows](#legacy-windows-support)
  60. ## Installation
  61. Install from PyPI with pip or your favorite tool.
  62. ```sh
  63. pip install rich-argparse
  64. ```
  65. ## Usage
  66. Simply pass `formatter_class` to the argument parser
  67. ```python
  68. import argparse
  69. from rich_argparse import RichHelpFormatter
  70. parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
  71. ...
  72. ```
  73. *rich-argparse* defines equivalents to all [argparse's standard formatters](
  74. https://docs.python.org/3/library/argparse.html#formatter-class):
  75. | `rich_argparse` formatter | equivalent in `argparse` |
  76. |-------------------------------------|---------------------------------|
  77. | `RichHelpFormatter` | `HelpFormatter` |
  78. | `RawDescriptionRichHelpFormatter` | `RawDescriptionHelpFormatter` |
  79. | `RawTextRichHelpFormatter` | `RawTextHelpFormatter` |
  80. | `ArgumentDefaultsRichHelpFormatter` | `ArgumentDefaultsHelpFormatter` |
  81. | `MetavarTypeRichHelpFormatter` | `MetavarTypeHelpFormatter` |
  82. Additional formatters are available in the `rich_argparse.contrib` [module](#additional-formatters).
  83. ## Output styles
  84. The default styles used by *rich-argparse* are carefully chosen to work in different light and dark
  85. themes.
  86. ### Customize the colors
  87. You can customize the colors of the output by modifying the `styles` dictionary on the formatter
  88. class. You can use any rich style as defined [here](https://rich.readthedocs.io/en/latest/style.html).
  89. *rich-argparse* defines and uses the following styles:
  90. ```python
  91. {
  92. 'argparse.args': 'cyan', # for positional-arguments and --options (e.g "--help")
  93. 'argparse.groups': 'dark_orange', # for group names (e.g. "positional arguments")
  94. 'argparse.help': 'default', # for argument's help text (e.g. "show this help message and exit")
  95. 'argparse.metavar': 'dark_cyan', # for metavariables (e.g. "FILE" in "--file FILE")
  96. 'argparse.prog': 'grey50', # for %(prog)s in the usage (e.g. "foo" in "Usage: foo [options]")
  97. 'argparse.syntax': 'bold', # for highlights of back-tick quoted text (e.g. "`some text`")
  98. 'argparse.text': 'default', # for descriptions, epilog, and --version (e.g. "A program to foo")
  99. 'argparse.default': 'italic', # for %(default)s in the help (e.g. "Value" in "(default: Value)")
  100. }
  101. ```
  102. For example, to make the description and epilog *italic*, change the `argparse.text` style:
  103. ```python
  104. RichHelpFormatter.styles["argparse.text"] = "italic"
  105. ```
  106. ### Customize the group name format
  107. You can change how the names of the groups (like `'positional arguments'` and `'options'`) are
  108. formatted by setting the `RichHelpFormatter.group_name_formatter` which is set to `str.title` by
  109. default. Any callable that takes the group name as an input and returns a str works:
  110. ```python
  111. RichHelpFormatter.group_name_formatter = str.upper # Make group names UPPERCASE
  112. ```
  113. ### Special text highlighting
  114. You can [highlight patterns](https://rich.readthedocs.io/en/stable/highlighting.html) in the
  115. arguments help and the description and epilog using regular expressions. By default,
  116. *rich-argparse* highlights patterns of `--options-with-hyphens` using the `argparse.args` style
  117. and patterns of `` `back tick quoted text` `` using the `argparse.syntax` style. You can control
  118. what patterns are highlighted by modifying the `RichHelpFormatter.highlights` list. To disable all
  119. highlights, you can clear this list using `RichHelpFormatter.highlights.clear()`.
  120. You can also add custom highlight patterns and styles. The following example highlights all
  121. occurrences of `pyproject.toml` in green:
  122. ```python
  123. # Add a style called `pyproject` which applies a green style (any rich style works)
  124. RichHelpFormatter.styles["argparse.pyproject"] = "green"
  125. # Add the highlight regex (the regex group name must match an existing style name)
  126. RichHelpFormatter.highlights.append(r"\b(?P<pyproject>pyproject\.toml)\b")
  127. # Pass the formatter class to argparse
  128. parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
  129. ...
  130. ```
  131. ### Colors in the `usage`
  132. The usage **generated by the formatter** is colored using the `argparse.args` and `argparse.metavar`
  133. styles. If you use a custom `usage` message in the parser, it will be treated as "plain text" and
  134. will **not** be colored by default. You can enable colors in user defined usage message through
  135. [console markup](https://rich.readthedocs.io/en/stable/markup.html) by setting
  136. `RichHelpFormatter.usage_markup = True`. If you enable this option, make sure to [escape](
  137. https://rich.readthedocs.io/en/stable/markup.html#escaping) any square brackets in the usage text.
  138. ### Disable console markup
  139. The text of the descriptions and epilog is interpreted as
  140. [console markup](https://rich.readthedocs.io/en/stable/markup.html) by default. If this conflicts
  141. with your usage of square brackets, make sure to [escape](
  142. https://rich.readthedocs.io/en/stable/markup.html#escaping) the square brackets or to disable
  143. markup globally with `RichHelpFormatter.text_markup = False`.
  144. Similarly the help text of arguments is interpreted as markup by default. It can be disabled using
  145. `RichHelpFormatter.help_markup = False`.
  146. ### Colors in `--version`
  147. If you use the `"version"` action from argparse, you can use console markup in the `version` string:
  148. ```python
  149. parser.add_argument(
  150. "--version", action="version", version="[argparse.prog]%(prog)s[/] version [i]1.0.0[/]"
  151. )
  152. ```
  153. Note that the `argparse.text` style is applied to the `version` string similar to the description
  154. and epilog.
  155. ### Rich descriptions and epilog
  156. You can use any rich renderable in the descriptions and epilog. This includes all built-in rich
  157. renderables like `Table` and `Markdown` and any custom renderables defined using the
  158. [Console Protocol](https://rich.readthedocs.io/en/stable/protocol.html#console-protocol).
  159. ```python
  160. import argparse
  161. from rich.markdown import Markdown
  162. from rich_argparse import RichHelpFormatter
  163. description = """
  164. # My program
  165. This is a markdown description of my program.
  166. * It has a list
  167. * And a table
  168. | Column 1 | Column 2 |
  169. | -------- | -------- |
  170. | Value 1 | Value 2 |
  171. """
  172. parser = argparse.ArgumentParser(
  173. description=Markdown(description, style="argparse.text"),
  174. formatter_class=RichHelpFormatter,
  175. )
  176. ...
  177. ```
  178. Certain features are **disabled** for arbitrary renderables other than strings, including:
  179. * Syntax highlighting with `RichHelpFormatter.highlights`
  180. * Styling with the `"argparse.text"` style defined in `RichHelpFormatter.styles`
  181. * Replacement of `%(prog)s` with the program name
  182. ## Working with subparsers
  183. Subparsers do not inherit the formatter class from the parent parser by default. You have to pass
  184. the formatter class explicitly:
  185. ```python
  186. subparsers = parser.add_subparsers(...)
  187. p1 = subparsers.add_parser(..., formatter_class=parser.formatter_class)
  188. p2 = subparsers.add_parser(..., formatter_class=parser.formatter_class)
  189. ```
  190. ## Generate help preview
  191. You can generate a preview of the help message for your CLI in SVG, HTML, or TXT formats using the
  192. `HelpPreviewAction` action. This is useful for including the help message in the documentation of
  193. your app. The action uses the
  194. [rich exporting API](https://rich.readthedocs.io/en/stable/console.html#exporting) internally.
  195. ```python
  196. import argparse
  197. from rich.terminal_theme import DIMMED_MONOKAI
  198. from rich_argparse import HelpPreviewAction, RichHelpFormatter
  199. parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
  200. ...
  201. parser.add_argument(
  202. "--generate-help-preview",
  203. action=HelpPreviewAction,
  204. path="help-preview.svg", # (optional) or "help-preview.html" or "help-preview.txt"
  205. export_kwds={"theme": DIMMED_MONOKAI}, # (optional) keywords passed to console.save_... methods
  206. )
  207. ```
  208. This action is hidden, it won't show up in the help message or in the parsed arguments namespace.
  209. Use it like this:
  210. ```sh
  211. python my_cli.py --generate-help-preview # generates help-preview.svg (default path specified above)
  212. # or
  213. python my_cli.py --generate-help-preview my-help.svg # generates my-help.svg
  214. # or
  215. COLUMNS=120 python my_cli.py --generate-help-preview # force the width of the output to 120 columns
  216. ```
  217. ## Additional formatters
  218. *rich-argparse* defines additional non-standard argparse formatters for some common use cases in
  219. the `rich_argparse.contrib` module. They can be imported with the `from rich_argparse.contrib import`
  220. syntax. The following formatters are available:
  221. * `ParagraphRichHelpFormatter`: A formatter similar to `RichHelpFormatter` that preserves paragraph
  222. breaks. A paragraph break is defined as two consecutive newlines (`\n\n`) in the help or
  223. description text. Leading and trailing trailing whitespace are stripped similar to
  224. `RichHelpFormatter`.
  225. _More formatters will be added in the future._
  226. ## Django support
  227. *rich-argparse* provides support for django's custom help formatter. You can instruct django to use
  228. *rich-argparse* with all built-in, extension libraries, and user defined commands in a django
  229. project by adding these two lines to the `manage.py` file:
  230. ```diff
  231. diff --git a/manage.py b/manage.py
  232. def main():
  233. """Run administrative tasks."""
  234. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')
  235. try:
  236. from django.core.management import execute_from_command_line
  237. except ImportError as exc:
  238. raise ImportError(
  239. "Couldn't import Django. Are you sure it's installed and "
  240. "available on your PYTHONPATH environment variable? Did you "
  241. "forget to activate a virtual environment?"
  242. ) from exc
  243. + from rich_argparse.django import richify_command_line_help
  244. + richify_command_line_help()
  245. execute_from_command_line(sys.argv)
  246. ```
  247. Alternatively, you can use the `DjangoRichHelpFormatter` class directly in your commands:
  248. ```diff
  249. diff --git a/my_app/management/commands/my_command.py b/my_app/management/commands/my_command.py
  250. from django.core.management.base import BaseCommand
  251. +from rich_argparse.django import DjangoRichHelpFormatter
  252. class Command(BaseCommand):
  253. def add_arguments(self, parser):
  254. + parser.formatter_class = DjangoRichHelpFormatter
  255. parser.add_argument("--option", action="store_true", help="An option")
  256. ...
  257. ```
  258. ## Optparse support
  259. *rich-argparse* now ships with experimental support for [optparse](
  260. https://docs.python.org/3/library/optparse.html).
  261. Import optparse help formatters from `rich_argparse.optparse`:
  262. ```python
  263. import optparse
  264. from rich_argparse.optparse import IndentedRichHelpFormatter # or TitledRichHelpFormatter
  265. parser = optparse.OptionParser(formatter=IndentedRichHelpFormatter())
  266. ...
  267. ```
  268. You can also generate a more helpful usage message by passing `usage=GENERATE_USAGE` to the
  269. parser. This is similar to the default behavior of `argparse`.
  270. ```python
  271. from rich_argparse.optparse import GENERATE_USAGE, IndentedRichHelpFormatter
  272. parser = optparse.OptionParser(usage=GENERATE_USAGE, formatter=IndentedRichHelpFormatter())
  273. ```
  274. Similar to `argparse`, you can customize the styles used by the formatter by modifying the
  275. `RichHelpFormatter.styles` dictionary. These are the same styles used by `argparse` but with
  276. the `optparse.` prefix instead:
  277. ```python
  278. RichHelpFormatter.styles["optparse.metavar"] = "bold magenta"
  279. ```
  280. Syntax highlighting works the same as with `argparse`.
  281. Colors in the `usage` are only supported when using `GENERATE_USAGE`.
  282. ## Legacy Windows support
  283. When used on legacy Windows versions like *Windows 7*, colors are disabled unless
  284. [colorama](https://pypi.org/project/colorama/) is used:
  285. ```python
  286. import argparse
  287. import colorama
  288. from rich_argparse import RichHelpFormatter
  289. colorama.init()
  290. parser = argparse.ArgumentParser(..., formatter_class=RichHelpFormatter)
  291. ...
  292. ```