documentation.md
This file
Path
docs/documentation.md
333 lines · 8.4 KiB · Markdown
Last changed by
Add example for Group Help Page in documentationAnurag Saxenabefore adoptiondfb15ee
History of this fileTake it
Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 1–52why, 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()18 @click.argument('name')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```52Add example for Group Help Page in documentationAnurag Saxenabefore adoptiondfb15ee
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(init, args=['--help'])91```92Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 93–187why, 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 Arguments115116{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text117by name. This should then be done via the docstring.118119A brief example:120121```{eval-rst}122.. click:example::123124 @click.command()125 @click.argument('filename')126 def touch(filename):127 """Print FILENAME."""128 click.echo(filename)129130.. click:run::131 invoke(touch, args=['--help'])132```133134Or more explicitly:135136```{eval-rst}137.. click:example::138139 @click.command()140 @click.argument('filename')141 def touch(filename):142 """Print FILENAME.143144 FILENAME is the name of the file to check.145 """146 click.echo(filename)147148.. click:run::149 invoke(touch, args=['--help'])150```151152## Showing Defaults153154To control the appearance of defaults pass `show_default`.155156```{eval-rst}157.. click:example::158159 @click.command()160 @click.option('--n', default=1, show_default=False, help='number of dots')161 def dots(n):162 click.echo('.' * n)163164.. click:run::165 invoke(dots, args=['--help'])166```167168For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.169170```{eval-rst}171.. click:example::172173 @click.command()174 @click.option('--n', default=1, show_default=True)175 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")176 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")177 def dots(n, gr, br):178 if gr:179 click.echo('Hello world!')180 click.echo('.' * n)181 if br:182 click.echo('-' * n)183184.. click:run::185 invoke(dots, args=['--help'])186```187Document show_envvar in Help Pages (#3166)Rowlando13before adoption2570bbc
lines 188–203why, one step back188## Showing Environment Variables189190To control the appearance of environment variables pass `show_envvar`.191192```{eval-rst}193.. click:example::194195 @click.command()196 @click.option('--username', envvar='USERNAME', show_envvar=True)197 def greet(username):198 click.echo(f'Hello {username}!')199200.. click:run::201 invoke(greet, args=['--help'])202```203Documentation.rst reST to MyST (#2980)Rowlando13before adoption5c1239b
lines 204–205why, one step back204## Click's Wrapping Behavior205Improve discoverability of Context.max_content_width (#3011)Rowlando13before adoptiona97412d
line 206why, one step back206Click'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 207–333why, one step back207208```{eval-rst}209.. click:example::210211 import click212213 @click.command()214 def cli():215 """216 This is a very long paragraph and as you217 can see wrapped very early in the source text218 but will be rewrapped to the terminal width in219 the final output.220221 This is222 a paragraph223 that is compacted.224 """225226.. click:run::227 invoke(cli, args=['--help'])228```229230## Escaping Click's Wrapping231232Sometimes 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.233234Example:235236```{eval-rst}237.. click:example::238239 import click240241 @click.command()242 def cli():243 """First paragraph.244245 \b246 This is247 a paragraph248 without rewrapping.249250 And this is a paragraph251 that will be rewrapped again.252 """253254.. click:run::255 invoke(cli, args=['--help'])256```257258To change the rendering maximum width, pass `max_content_width` when calling the command.259260```bash261cli(max_content_width=120)262```263264## Truncating Help Texts265266Click 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.267268Example:269270```{eval-rst}271.. click:example::272273 import click274275 @click.command()276 def cli():277 """First paragraph.278 \f279280 Words to not be included.281 """282283.. click:run::284 invoke(cli, args=['--help'])285```286287(doc-meta-variables)=288289## Placeholder / Meta Variable290291The 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.292293```{eval-rst}294.. click:example::295296 # This controls entry on the usage line.297 @click.command(options_metavar='[[options]]')298 @click.option('--count', default=1, help='number of greetings',299 metavar='<int>')300 @click.argument('name', metavar='<name>')301 def hello(name: str, count: int) -> None:302 """This script prints 'hello <name>' a total of <count> times."""303 for x in range(count):304 click.echo(f"Hello {name}!")305306# Example usage:307308.. click:run::309 invoke(hello, args=['--help'])310311```312313## Help Parameter Customization314315Help 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.316317This example changes the default parameters to `-h` and `--help`318instead of just `--help`:319320```{eval-rst}321.. click:example::322323 import click324325 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])326327 @click.command(context_settings=CONTEXT_SETTINGS)328 def cli():329 pass330331.. click:run::332 invoke(cli, ['-h'])333```