Skip to content
Myr

documentation.md

This file

Path

docs/documentation.md

343 lines · 9.7 KiB · Markdown

Last changed by

Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a

History of this file

Take it

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 1–17why, one step back
1# Help Pages
23```{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()

Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a

line 18why, one step back
18 @click.argument('name', help='The name to print')

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 19–52why, one step back
19 @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```52

Add example for Group Help Page in documentation (#3472)Rowlando13before adoption5b1aba8

lines 53–92why, one step back
53## Group Help Page
5455The 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```92

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 93–115why, one step back
93## Command Epilog Help
9495The 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 Arguments115

Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a

lines 116–119why, one step back
116{class}`click.argument` accepts an optional `help` parameter that is shown in
117the ``Positional arguments`` section of the help page. You can still document118arguments 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

lines 120–126why, one step back
120
121A brief example:122123```{eval-rst}124.. click:example::125126 @click.command()

Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a

line 127why, one step back
127 @click.argument('filename', help='The file to print.')

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 128–135why, one step back
128 def touch(filename):
129 """Print FILENAME."""130 click.echo(filename)131132.. click:run::133 invoke(touch, args=['--help'])134```135

Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a

line 136why, one step back
136Or more explicitly in the docstring:

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 137–189why, one step back
137
138```{eval-rst}139.. click:example::140141 @click.command()142 @click.argument('filename')143 def touch(filename):144 """Print FILENAME.145146 FILENAME is the name of the file to check.147 """148 click.echo(filename)149150.. click:run::151 invoke(touch, args=['--help'])152```153154## Showing Defaults155156To control the appearance of defaults pass `show_default`.157158```{eval-rst}159.. click:example::160161 @click.command()162 @click.option('--n', default=1, show_default=False, help='number of dots')163 def dots(n):164 click.echo('.' * n)165166.. click:run::167 invoke(dots, args=['--help'])168```169170For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.171172```{eval-rst}173.. click:example::174175 @click.command()176 @click.option('--n', default=1, show_default=True)177 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")178 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")179 def dots(n, gr, br):180 if gr:181 click.echo('Hello world!')182 click.echo('.' * n)183 if br:184 click.echo('-' * n)185186.. click:run::187 invoke(dots, args=['--help'])188```189

Document show_envvar in Help Pages (#3166)Rowlando13before adoption2570bbc

lines 190–205why, one step back
190## Showing Environment Variables
191192To control the appearance of environment variables pass `show_envvar`.193194```{eval-rst}195.. click:example::196197 @click.command()198 @click.option('--username', envvar='USERNAME', show_envvar=True)199 def greet(username):200 click.echo(f'Hello {username}!')201202.. click:run::203 invoke(greet, args=['--help'])204```205

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 206–207why, one step back
206## Click's Wrapping Behavior
207

Improve discoverability of Context.max_content_width (#3011)Rowlando13before adoptiona97412d

line 208why, one step back
208Click'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 209–314why, one step back
209
210```{eval-rst}211.. click:example::212213 import click214215 @click.command()216 def cli():217 """218 This is a very long paragraph and as you219 can see wrapped very early in the source text220 but will be rewrapped to the terminal width in221 the final output.222223 This is224 a paragraph225 that is compacted.226 """227228.. click:run::229 invoke(cli, args=['--help'])230```231232## Escaping Click's Wrapping233234Sometimes 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.235236Example:237238```{eval-rst}239.. click:example::240241 import click242243 @click.command()244 def cli():245 """First paragraph.246247 \b248 This is249 a paragraph250 without rewrapping.251252 And this is a paragraph253 that will be rewrapped again.254 """255256.. click:run::257 invoke(cli, args=['--help'])258```259260To change the rendering maximum width, pass `max_content_width` when calling the command.261262```bash263cli(max_content_width=120)264```265266## Truncating Help Texts267268Click 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.269270Example:271272```{eval-rst}273.. click:example::274275 import click276277 @click.command()278 def cli():279 """First paragraph.280 \f281282 Words to not be included.283 """284285.. click:run::286 invoke(cli, args=['--help'])287```288289(doc-meta-variables)=290291## Placeholder / Meta Variable292293The 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.294295```{eval-rst}296.. click:example::297298 # This controls entry on the usage line.299 @click.command(options_metavar='[[options]]')300 @click.option('--count', default=1, help='number of greetings',301 metavar='<int>')302 @click.argument('name', metavar='<name>')303 def hello(name: str, count: int) -> None:304 """This script prints 'hello <name>' a total of <count> times."""305 for x in range(count):306 click.echo(f"Hello {name}!")307308# Example usage:309310.. click:run::311 invoke(hello, args=['--help'])312313```314

Mark commands as optional in the synopsis (#3507)Rowlando13before adoption97210f2

lines 315–322why, one step back
315```{admonition} Optional elements are bracketed
316:class: note317318 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.319320 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.321```322

Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b

lines 323–343why, one step back
323## Help Parameter Customization
324325Help 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 also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.326327This example changes the default parameters to `-h` and `--help`328instead of just `--help`:329330```{eval-rst}331.. click:example::332333 import click334335 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])336337 @click.command(context_settings=CONTEXT_SETTINGS)338 def cli():339 pass340341.. click:run::342 invoke(cli, ['-h'])343```