rich-click CLI tool
rich-click comes with a CLI tool that allows you to format the Click help output for any CLI that uses Click.
$ rich-click --helpUsage: rich-click [OPTIONS] SCRIPT | MODULE[:CLICK_COMMAND] ... The rich-click CLI provides richly formatted help output from any tool using click, formatted with rich. Full docs here: https://ewels.github.io/rich-click/latest/documentation/rich_click_cli/ The rich-click command line tool can be prepended before any Python package using native click to provide attractive richified click help output. For example, if you have a package called my_package that uses click, you can run: >>> rich-click my_package --help [..truncated..]
To use, simply prefix rich-click to the command. Here are a few real world examples:
$ rich-click flask --helpUsage: flask [OPTIONS] COMMAND [ARGS]... A general utility script for Flask applications. An application to load must be given with the '--app' option, 'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file in the current directory. ╭─ Options ────────────────────────────────────────────────────────────────────╮ │ --env-file -e FILE Load environment variables from this file, │ │ taking precedence over those set by '.env' │ │ and '.flaskenv'. Variables set directly in │ │ the environment take highest precedence. │ │ python-dotenv must be installed. │ │ --app -A IMPORT The Flask application or factory function to │ │ load, in the form 'module:name'. Module can │ │ be a dotted import or file path. Name is not │ │ required if it is 'app', 'application', │ │ 'create_app', or 'make_app', and can be │ │ 'name(args)' to pass arguments. │ │ --debug/--no-debug Set debug mode. │ │ --version Show the Flask version. │ │ --help Show this message and exit. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ───────────────────────────────────────────────────────────────────╮ │ routes Show the routes for the app. │ │ run Run a development server. │ │ shell Run a shell in the app context. │ ╰──────────────────────────────────────────────────────────────────────────────╯
$ rich-click celery --helpUsage: celery [OPTIONS] [COMMAND] [ARGS]... Celery command entrypoint. ╭─ Options ────────────────────────────────────────────────────────────────────╮ │ --app -A TEXT │ │ --broker -b TEXT │ │ --result-backend TEXT │ │ --loader TEXT │ │ --config TEXT │ │ --workdir PATH │ │ --no-color -C │ │ --quiet -q │ │ --version │ │ --skip-checks Skip Django core checks on startup. Setting the │ │ SKIP_CHECKS environment variable to any │ │ non-empty string will have the same effect. │ │ --help Show this message and exit. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ───────────────────────────────────────────────────────────────────╮ │ amqp AMQP Administration Shell. │ │ beat Start the beat periodic task scheduler. │ │ call Call a task by name. │ │ control Send the COMMAND control command to the workers. │ │ events Event-stream utilities. │ │ graph The ``celery graph`` command. │ │ inspect Inspect the workers by sending them the COMMAND inspect command. │ │ list Get info from broker. │ │ logtool The ``celery logtool`` command. │ │ migrate Migrate tasks from one broker to another. │ │ multi Start multiple worker instances. │ │ purge Erase all messages from all known task queues. │ │ report Shows information useful to include in bug-reports. │ │ result Print the return value for a given task id. │ │ shell Start shell session with convenient access to celery symbols. │ │ status Show list of workers that are online. │ │ upgrade Perform upgrade between versions. │ │ worker Start worker instance. │ ╰──────────────────────────────────────────────────────────────────────────────╯
$ rich-click dagster --helpUsage: dagster [OPTIONS] COMMAND [ARGS]... CLI tools for working with Dagster. ╭─ Options ────────────────────────────────────────────────────────────────────╮ │ --version -v Show the version and exit. │ │ --help -h Show this message and exit. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ───────────────────────────────────────────────────────────────────╮ │ asset Commands for working with Dagster assets. │ │ code-server Commands for working with Dagster code servers. │ │ debug Commands for helping debug Dagster issues by dumping or loading │ │ artifacts from specific runs. │ │ definitions Commands for working with Dagster definitions. │ │ dev Start a local deployment of Dagster, including │ │ dagster-webserver running on localhost and the dagster-daemon │ │ running in the background │ │ instance Commands for working with the current Dagster instance. │ │ job Commands for working with Dagster jobs. │ │ project Commands for bootstrapping new Dagster projects and code │ │ locations. │ │ run Commands for working with Dagster job runs. │ │ schedule Commands for working with Dagster schedules. │ │ sensor Commands for working with Dagster sensors. │ ╰──────────────────────────────────────────────────────────────────────────────╯
If the CLI is not installed as a script, you can also pass the location with:
<module_name>:<click_command_name><module_name><path>
For example, if you have a file located at path/to/my/cli.py, and the Click Command object is named main, then you can run:
rich-click path.to.my.cli:mainrich-click path.to.my.clirich-click path/to/my/cli.py
In the first case, the object will be imported and called, i.e. from path.to.my.cli import main then main().
In the other two cases, the file will be run with __name__ as "__main__".
Render help text as HTML or SVG
Section titled “Render help text as HTML or SVG”You can also use rich-click --output=html [command] to render rich HTML for help text, or rich-click --output=svg [command] to generate an SVG.
This works for RichCommands as well as normal click Commands.
SVG example:
$ rich-click --output svg app:main --help<svg class="rich-terminal" viewBox="0 0 994 416.0" xmlns="http://www.w3.org/2000/svg"> <!-- Generated with Rich https://www.textualize.io --> <style> @font-face { font-family: "Fira Code"; src: local("FiraCode-Regular"), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2" ), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff"); font-style: normal; font-weight: 400; } [..truncated..]
HTML example:
$ rich-click --output html app:main --help<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body { color: #000000; background-color: #ffffff; } </style> </head> <body> [..truncated..]
SVG and HTML generated from docs/code_snippets/rich_click_cli/app.py
Typer support
Section titled “Typer support”As of 1.9.0, the rich-click CLI supports patching Typer.
You don’t need to do anything special to patch Typer CLIs; it works out of the box.
The main reason to patch Typer CLIs is to get access to rich-click’s themes. Another reason is to print HTML and SVG.
Here is an example of overriding a Typer CLI with a rich-click theme:
# /// script# dependencies = ["rich-click>=1.9", "typer>=0.15"]# ///
# This example comes from the Typer docs:# https://typer.tiangolo.com/tutorial/commands/help/#help-panels-for-commandsimport typer
@app.command()def create(username: str): """[green]Create[/green] a new user. :sparkles:""" print(f"Creating user: {username}")
@app.command()def delete(username: str): """[red]Delete[/red] a user. :fire:""" print(f"Deleting user: {username}")
@app.command(rich_help_panel="Utils and Configs")def config(configuration: str): """[blue]Configure[/blue] the system. :wrench:""" print(f"Configuring the system with: {configuration}")
@app.command(rich_help_panel="Utils and Configs")def sync(): """[blue]Synchronize[/blue] the system or something fancy like that. :recycle:""" print("Syncing the system")
@app.command(rich_help_panel="Help and Others")def help(): """Get [yellow]help[/yellow] with the system. :question:""" print("Opening help portal...")
@app.command(rich_help_panel="Help and Others")def report(): """[yellow]Report[/yellow] an issue. :bug:""" print("Please open a new issue online, not a direct message")
if __name__ == "__main__": app()Output
$ rich-click --theme magenta1-nu typer_example.py --helpUsage: typer_example.py [OPTIONS] COMMAND [ARGS]... ═ Options ════════════════════════════════════════════════════════════════════ --install-completion Install completion for the current shell. --show-completion Show completion for the current shell, to copy it or customize the installation. --help Show this message and exit. ═ Commands ═══════════════════════════════════════════════════════════════════ create Create a new user. ✨ delete Delete a user. 🔥 ═ Utils and Configs ══════════════════════════════════════════════════════════ config Configure the system. 🔧 sync Synchronize the system or something fancy like that. ♻ ═ Help and Others ════════════════════════════════════════════════════════════ help Get help with the system. ❓ report Report an issue. 🐛
Notes on how the rich-click CLI works
Section titled “Notes on how the rich-click CLI works”Under the hood, the rich-click CLI is patching the click module, and replacing the Click decorators and click.Command, click.Group, etc. objects with their equivalent rich-click versions.
Sometimes, a subclassed click.Command will overwrite one of these methods:
click.Command.format_usageclick.Command.format_help_textclick.Command.format_optionsclick.MultiCommand.format_commandsclick.Command.format_epilog
Patching Click internals can mess with method resolution order,
since by the time the downstream library subclasses the click.Command, it will be a RichCommand, and the subclass’s method will take precedence over the RichCommand’s methods.
The problem is that rich-click’s methods can be incompatible or at least stylistically incongruous with the base Click help text rendering.
To solve this, rich-click checks whether a method comes from a “true” RichCommand subclass or if it just looks that way due to patching.
If RichCommand is “properly” subclassed, the override is allowed.
If the subclass is only a result of the patching operation, we ignore the aforementioned methods and use the rich-click implementation.
Long story short, the rich-click CLI is safe to subclassing when it is the user’s intent to subclass a rich-click object. (This is so that you can use other nifty features of the CLI such as the --output option on your own rich-click CLIs)
That said, custom, non-rich-click implementations are ignored.
Additional hacks are implemented to provide first-class support for Typer.
When a Click object subclass is defined, we detect whether it is a Typer subclass during the call to the metaclass __init__.
When Typer is detected, we do additional overrides to resolve differences between Typer’s and rich-click’s APIs.
Using patch() as an end user
Section titled “Using patch() as an end user”The functionality that rich-click uses to patch Click internals is available for use by rich-click end users,
and it occasionally comes in handy outside of the rich-click CLI.
In some situations, you might be registering a command from another Click CLI that does not use rich-click:
from some_library import another_cli
def cli(): pass
# `another_cli` will NOT have rich-click markup. :(cli.add_command(another_cli)In this situation, another_cli retains its original help text behavior.
In order to make another_cli work with rich-click, you need to patch click before you import another_cli.
You can patch Click with rich_click.patch.patch like this:
patch()
from some_library import another_cli # noqa: E402
def cli(): pass
# `another_cli` will have rich-click markup. :)cli.add_command(another_cli)