documentation.md
This file
Path
docs/documentation.md
347 lines · 10.0 KiB · Markdown
Last changed by
Merge stable into main (#3876)Rowlando13before adoption3cbaa76
History of this fileTake it
Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 1–17why, one step back1# Help Pages23```{currentmodule} click4```56Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.78## Help Texts910Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.1112Simple example:1314```{eval-rst}15.. click:example::1617 @click.command()Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
line 18why, one step back18 @click.argument('name', help='The name to print.')Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 19–52why, one step back19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):23 if name:24 click.echo(f"Hello {name}!")25 else:26 click.echo("Hello!")2728.. click:run::29 invoke(hello, args=['--help'])30```3132## Command Short Help3334For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`:3536```{eval-rst}37.. click:example::3839 import click4041 @click.group()42 def cli():43 """A simple command line tool."""4445 @cli.command('init', short_help='init the repo')46 def init():47 """Initializes the repository."""4849.. click:run::50 invoke(cli, args=['--help'])51```52Merge branch 'stable'Kevin Deldyckebefore adoption3a40e43
lines 53–92why, one step back53## Group Help Page5455The group help prints sub commands, options, epilog help, and arguments, and prints them together.5657```{eval-rst}58.. click:example::5960 import click6162 @click.group(63 help="Example Click app with subcommands, options, and positional arguments.",64 epilog=("Examples:\n\n\b\n python hello.py greet Alice --count 2\n"),65 )66 def cli() -> None:67 """Run the example CLI."""6869 @cli.command()70 @click.argument("name")71 @click.option(72 "--count",73 default=1,74 show_default=True,75 type=click.IntRange(1, None),76 help="Number of greetings to print.",77 )78 @click.option(79 "--greeting",80 default="Hello",81 show_default=True,82 help="Greeting prefix to use.",83 )84 def greet(name: str, count: int, greeting: str) -> None:85 """Greet NAME one or more times."""86 for _ in range(count):87 click.echo(f"{greeting} {name}!")8889.. click:run::90 invoke(cli, args=['--help'])91```92Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 93–115why, one step back93## Command Epilog Help9495The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.9697```{eval-rst}98.. click:example::99100 import click101102 @click.command(103 epilog='See https://example.com for more details',104 )105 def init():106 """Initializes the repository."""107108.. click:run::109 invoke(init, args=['--help'])110```111112(documenting-arguments)=113114## Documenting Arguments115Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
line 116why, one step back116{class}`click.argument` accepts an optional `help` parameter that is shown inPre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
line 117why, one step back117the `Positional arguments` section of the help page. You can still documentAdd help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
lines 118–119why, one step back118arguments in the command docstring, especially when you want to describe them119in the main help text by name.Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
line 120why, one step back120Merge stable into main (#3876)Rowlando13before adoption3cbaa76
lines 121–124why, one step back121The section shows up as soon as one argument of the command has a `help`. It122then lists every argument, so it always matches the usage line. Arguments with123no `help` are listed with an empty description.124Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 125–130why, one step back125A brief example:126127```{eval-rst}128.. click:example::129130 @click.command()Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
line 131why, one step back131 @click.argument('filename', help='The file to print.')Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 132–139why, one step back132 def touch(filename):133 """Print FILENAME."""134 click.echo(filename)135136.. click:run::137 invoke(touch, args=['--help'])138```139Add help parameter to arguments (#3473)Kevin Deldyckebefore adoptionc480210
line 140why, one step back140Or more explicitly in the docstring:Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 141–193why, one step back141142```{eval-rst}143.. click:example::144145 @click.command()146 @click.argument('filename')147 def touch(filename):148 """Print FILENAME.149150 FILENAME is the name of the file to check.151 """152 click.echo(filename)153154.. click:run::155 invoke(touch, args=['--help'])156```157158## Showing Defaults159160To control the appearance of defaults pass `show_default`.161162```{eval-rst}163.. click:example::164165 @click.command()166 @click.option('--n', default=1, show_default=False, help='number of dots')167 def dots(n):168 click.echo('.' * n)169170.. click:run::171 invoke(dots, args=['--help'])172```173174For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.175176```{eval-rst}177.. click:example::178179 @click.command()180 @click.option('--n', default=1, show_default=True)181 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")182 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")183 def dots(n, gr, br):184 if gr:185 click.echo('Hello world!')186 click.echo('.' * n)187 if br:188 click.echo('-' * n)189190.. click:run::191 invoke(dots, args=['--help'])192```193Document show_envvar in Help Pages (#3166)Rowlando13before adoption2570bbc
lines 194–209why, one step back194## Showing Environment Variables195196To control the appearance of environment variables pass `show_envvar`.197198```{eval-rst}199.. click:example::200201 @click.command()202 @click.option('--username', envvar='USERNAME', show_envvar=True)203 def greet(username):204 click.echo(f'Hello {username}!')205206.. click:run::207 invoke(greet, args=['--help'])208```209Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 210–211why, one step back210## Click's Wrapping Behavior211Improve discoverability of Context.max_content_width (#3011)Rowlando13before adoptiona97412d
line 212why, one step back212Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal to a maximum of 80 characters by default, but this can be modified with {attr}`~Context.max_content_width`. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 213–318why, one step back213214```{eval-rst}215.. click:example::216217 import click218219 @click.command()220 def cli():221 """222 This is a very long paragraph and as you223 can see wrapped very early in the source text224 but will be rewrapped to the terminal width in225 the final output.226227 This is228 a paragraph229 that is compacted.230 """231232.. click:run::233 invoke(cli, args=['--help'])234```235236## Escaping Click's Wrapping237238Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text.239240Example:241242```{eval-rst}243.. click:example::244245 import click246247 @click.command()248 def cli():249 """First paragraph.250251 \b252 This is253 a paragraph254 without rewrapping.255256 And this is a paragraph257 that will be rewrapped again.258 """259260.. click:run::261 invoke(cli, args=['--help'])262```263264To change the rendering maximum width, pass `max_content_width` when calling the command.265266```bash267cli(max_content_width=120)268```269270## Truncating Help Texts271272Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker.273274Example:275276```{eval-rst}277.. click:example::278279 import click280281 @click.command()282 def cli():283 """First paragraph.284 \f285286 Words to not be included.287 """288289.. click:run::290 invoke(cli, args=['--help'])291```292293(doc-meta-variables)=294295## Placeholder / Meta Variable296297The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs.298299```{eval-rst}300.. click:example::301302 # This controls entry on the usage line.303 @click.command(options_metavar='[[options]]')304 @click.option('--count', default=1, help='number of greetings',305 metavar='<int>')306 @click.argument('name', metavar='<name>')307 def hello(name: str, count: int) -> None:308 """This script prints 'hello <name>' a total of <count> times."""309 for x in range(count):310 click.echo(f"Hello {name}!")311312# Example usage:313314.. click:run::315 invoke(hello, args=['--help'])316317```318Merge stable into main (#3521)Rowlando13before adoption1a994ad
lines 319–326why, one step back319```{admonition} Optional elements are bracketed320:class: note321322 The usage line follows a consistent convention: an element is optional when it is enclosed in square brackets and required when it appears outside them. A required argument appears as `FOO` and an optional one as `[FOO]`, with a variadic argument adding a trailing `...` (so `[FOO]...`). A single pair of brackets can group several tokens, so a chained group renders an extra command and its arguments as one optional, repeatable unit: `[COMMAND2 [ARGS]...]...`. A {class}`Group` that can run without naming a subcommand (`invoke_without_command=True`) also brackets the leading command, showing `[COMMAND]` instead of `COMMAND`. The `[OPTIONS]` placeholder is always bracketed, since adding options is itself optional.323324 This mirrors the conventional utility-argument syntax for optional arguments and operands ([POSIX §12.1](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html), [`man-pages(7)`](https://man7.org/linux/man-pages/man7/man-pages.7.html)), where a bracketed expression followed by `...` denotes zero or more occurrences. A subcommand name is a positional operand, so Click brackets it under the same rule.325```326Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 327–328why, one step back327## Help Parameter Customization328Fix parsing when a parameter is named `help` (#3678)Rowlando13before adoptionb67832c
line 329why, one step back329Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click resolves conflicts automatically: an option reusing one of the help option names takes it over, and the default help parameter is dropped once all its names are taken. A parameter merely named `help`, like `click.argument("help")`, does not disable it: both keep working independently.Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 330–347why, one step back330331This example changes the default parameters to `-h` and `--help`332instead of just `--help`:333334```{eval-rst}335.. click:example::336337 import click338339 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])340341 @click.command(context_settings=CONTEXT_SETTINGS)342 def cli():343 pass344345.. click:run::346 invoke(cli, ['-h'])347```