Skip to content
Myr

More automated docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent fcd6d32 · Browse files · 6 files+67 added−68 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+67 added−68 removed

  • other:+67 added−68 removed

6 files+67 added−68 removed

modified:docs/advanced.rst+6 added-2 removed
23 unmodified lines
24aliases on the help page to avoid confusion.2526This following example implements a subclass of :class:`Group` that27accepts a prefix for a command. So if there is a command called28``push`` it would accept ``pus`` as alias if it's unique::28``push`` it would accept ``pus`` as alias if it's unique:2930.. click:example::3132 class AliasedGroup(click.Group):3334 def get_command(self, ctx, cmd_name):35 rv = click.Group.get_command(self, ctx, cmd_name)
6 unmodified lines
42 elif len(matches) == 1:43 return click.Group.get_command(self, ctx, matches[0])44 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))4544And it can be used like this then::46And it can be used like this then:4748.. click:example::4950 @click.command(cls=AliasedGroup)51 def cli():52 pass53
7 unmodified lines
modified:docs/clickdoctools.py+1 added
116 unmodified lines
117118 def __init__(self):119 self.namespace = {120 'click': click,121 '__file__': 'dummy.py',122 }123124 def declare(self, source):125 code = compile(source, '<docs>', 'exec')
127 unmodified lines
modified:docs/commands.rst+20 added-29 removed
16 unmodified lines
1718For groups and multi commands the situation looks different. In that case19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs21when an inner command runs::21when an inner command runs:2223 import click23.. click:example::2425 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):
2 unmodified lines
30 @cli.command()31 def sync():32 print('Synching')3334 if __name__ == '__main__':35 cli()34Here is what this looks like:3537Here is what this looks like::36.. click:run::3739 $ python tool.py40 Usage: tool.py [OPTIONS] COMMAND [ARGS]...38 invoke(cli, prog_name='tool.py')39 println()40 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])4142 Commands:43 sync 4445 Options:46 --debug / --no-debug 47 --help Show this message and exit.48 49 $ python tool.py --debug sync50 Debug mode is on51 Synching 5242Nested Handling and Contexts43----------------------------4445As you can see from the earlier example the basic command group accepts a
12 unmodified lines
58case the context is passed as first argument.5960The context can also carry a program specified object that can be61used for the program's purposes. What this means is that you can build a73script like this::62script like this:6375 import click64.. click:example::6566 @click.group()67 @click.option('--debug/--no-debug', default=False)68 @click.pass_context
30 unmodified lines
99state and then storing it on the context and then to use a custom100decorator to find the most recent object of this sort and pass it as first101argument.102114For instance the :func:`pass_obj` decorator can be implemented like this::103For instance the :func:`pass_obj` decorator can be implemented like this:104116 import click105.. click:example::106107 from functools import update_wrapper108109 def pass_obj(f):110 @click.pass_context
20 unmodified lines
131always invoked instead of showing the help page. The context object also132includes information about if the invocation would go to a subcommand or133not.134145Example::135Example:136147 import click137.. click:example::138139 @click.group(invoke_without_command=True)140 @click.pass_context141 def cli(ctx):
5 unmodified lines
147 @cli.command()148 def sync():149 print('The subcommand')150161 if __name__ == '__main__':162 cli()163151And how it works in practice::152153 $ python tool.py 154 I was invoked without subcommand
9 unmodified lines
164In addition to using :func:`click.group` you can also build your own165custom multi commands. This is useful when you want to support commands166being loaded lazily from plugins.167181A custom multi command just needs to implement a list and load method::168A custom multi command just needs to implement a list and load method:169170.. click:example::171172 import click173 import os174175 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')
21 unmodified lines
197198 if __name__ == '__main__':199 cli()200212These custom classes can also be used with decorators::201These custom classes can also be used with decorators:202203.. click:example::204205 @click.command(cls=MyCLI)206 def cli():207 pass
modified:docs/complex.rst+15 added-5 removed
71 unmodified lines
72case we use the basic :func:`click.group` which allows us to register73other click commands below it.7475For this command we also want to accept some parameters that configure the76state of our tool::76state of our tool:7778.. click:example::7980 import os81 import click8283
29 unmodified lines
113The First Child Command114```````````````````````115116So let's add our first child command to it. Let's go with the clone115command::117command:118119.. click:example::120121 @cli.command()122 @click.argument('src')123 @click.argument('dest', required=False)124 def clone(src, dest):
3 unmodified lines
128you can imagine one way is to use the :func:`pass_context` function which129again will make our callback also get the context passed on which we130memorized the repo. Even better there is a second version of this131decorator called :func:`pass_obj` which will just pass the stored object,128in our case the repo::132in our case the repo:133134.. click:example::135136 @cli.command()137 @click.argument('src')138 @click.argument('dest', required=False)139 @click.pass_obj
20 unmodified lines
160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory which will create decorators for us that find objects. So in our163case we know that we want to find the closest ``Repo`` object. So let's158make a decorator for this::164make a decorator for this:165166.. click:example::167168 pass_repo = click.make_pass_decorator(Repo)169170If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a163repo instead of something else::171repo instead of something else:172173.. click:example::174175 @cli.command()176 @click.argument('src')177 @click.argument('dest', required=False)178 @pass_repo
2 unmodified lines
modified:docs/documentation.rst+18 added-28 removed
9 unmodified lines
1011Commands and options accept help arguments. In case of commands the doc12string of the function is automatically used if provided.1314Simple example::14Simple example:1516.. click:example::1718 @click.command()19 @click.option('--count', default=1, help='number of greetings')20 @click.argument('name')21 def hello(count, name):22 """This script prints hello NAME COUNT times."""23 for x in range(count):24 print('Hello %s!' % name)2524And what it looks like::26And what it looks like:2726 $ python hello.py --help27 Usage: hello.py [OPTIONS] NAME28.. click:run::2929 This script prints hello NAME COUNT times.30 invoke(hello, args=['--help'])3131 Options:32 --count=COUNT number of greetings33 --help Show this message and exit.3432Arguments cannot be documented this way. This is to follow general33convention of Unix tools to use arguments only for the most necessary34things and to document them in the introduction text by referring to them35by name.
3 unmodified lines
3940Options and parameters accept a ``metavar`` argument that can change the41meta variable in the help page. The default version is the parameter name42in uppercase with underscores and sometimes annotated differently if46optional. This can be customized at all levels::43optional. This can be customized at all levels:4445.. click:example::4647 @click.command(options_metavar='<options>')48 @click.option('--count', default=1, help='number of greetings',49 metavar='<int>')50 @click.argument('name', metavar='<name>')
1 unmodified line
52 """This script prints hello <name> <int> times."""53 for x in range(count):54 print('Hello %s!' % name)5557Example::56Example:5759 Usage: hello.py <options> <name>58.. click:run::5961 This script prints hello <name> <int> times.6263 Options:64 --count=<int> number of greetings65 --help Show this message and exit.60 invoke(hello, args=['--help'])61 6263Command Short Help64------------------6566For commands a short help is generated. By default it's the first part67(until the first dot) of the help message of the command unless it's too73long. This can also be overridden::68long. This can also be overridden:6970.. click:example::7172 @click.group()73 def cli():74 """A simple command line tool."""75
4 unmodified lines
80 @cli.command('delete', short_help='delete the repo')81 def delete():82 """Deletes the repository."""8387And what it looks like::84And what it looks like:8589 Usage: repo.py [OPTIONS] COMMAND [ARGS]...86.. click:run::8791 A simple command line tool.9293 Commands:94 delete delete the repo95 init init the repo9697 Options:98 --help Show this message and exit.88 invoke(cli, prog_name='repo.py')
modified:docs/setuptools.rst+7 added-4 removed
23 unmodified lines
24 yourpackage/25 cli.py26 setup.py2728Contents of ``cli.py``::28Contents of ``cli.py``:2930.. click:example::3132 import click3334 @click.command()35 def cli():
35 unmodified lines
71 $ virtualenv venv72 $ . venv/bin/activate73 $ pip install --editable .7473Afterwards your command should be available::75Afterwards your command should be available:7675 $ yourscript76 Hello World!77.. click:run::7879 invoke(cli, prog_name='yourscript', prog_prefix='')