rename extension from .rst to .md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jaron Rosenau · committed by Jaron Rosenau · parent 781d6a8 · Browse files · 2 files·+342 added−342 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+342 added−342 removed
- other:+342 added−342 removed
Provenance
- Commit
a29ec1a- Tree
ba53e43- Author
Jaron Rosenau <jaron.rosenau@gmail.com>- Committer
Jaron Rosenau <jaron.rosenau@gmail.com>- Parent
781d6a8
2 files changed+342 added−342 removed
added:docs/commands-and-groups.md+342 added
1+Basic Commands, Groups, Context2+================================3+4+.. currentmodule:: click5+6+Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7+8+.. contents::9+ :depth: 210+ :local:11+12+Commands13+--------------------14+15+Basic Command Example16+^^^^^^^^^^^^^^^^^^^^^^^17+A simple command decorator takes no arguments.18+19+.. click:example::20+ @click.command()21+ @click.option('--count', default=1)22+ def hello(count):23+ for x in range(count):24+ click.echo("Hello!")25+26+.. click:run::27+ invoke(hello, args=['--count', '2',])28+29+Renaming Commands30+^^^^^^^^^^^^^^^^^^^31+By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.32+33+.. click:example::34+ @click.command('say-hello')35+ @click.option('--count', default=1)36+ def hello(count):37+ for x in range(count):38+ click.echo("Hello!")39+40+.. click:run::41+ invoke(hello, args=['--count', '2',])42+43+Deprecating Commands44+^^^^^^^^^^^^^^^^^^^^^^45+To mark a command as deprecated pass in ``deprecated=True``46+47+.. click:example::48+ @click.command('say-hello', deprecated=True)49+ @click.option('--count', default=1)50+ def hello(count):51+ for x in range(count):52+ click.echo("Hello!")53+54+.. click:run::55+ invoke(hello, args=['--count', '2',])56+57+Groups58+------------59+60+Basic Group Example61+^^^^^^^^^^^^^^^^^^^^^62+A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.63+64+.. click:example::65+ @click.group()66+ def greeting():67+ click.echo('Starting greeting ...')68+69+ @greeting.command('say-hello')70+ @click.option('--count', default=1)71+ def hello(count):72+ for x in range(count):73+ click.echo("Hello!")74+75+At the top level:76+77+.. click:run::78+79+ invoke(greeting)80+81+At the command level:82+83+.. click:run::84+85+ invoke(greeting, args=['say-hello'])86+ invoke(greeting, args=['say-hello', '--help'])87+88+As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).89+90+Renaming Groups91+^^^^^^^^^^^^^^^^^92+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.93+94+.. click:example::95+ @click.group('greet-someone')96+ def greeting():97+ click.echo('Starting greeting ...')98+99+ @greeting.command('say-hello')100+ @click.option('--count', default=1)101+ def hello(count):102+ for x in range(count):103+ click.echo("Hello!")104+105+.. click:run::106+107+ invoke(greeting, args=['say-hello'])108+109+Group Invocation Without Command110+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111+112+By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.113+114+.. click:example::115+116+ @click.group(invoke_without_command=True)117+ @click.pass_context118+ def cli(ctx):119+ if ctx.invoked_subcommand is None:120+ click.echo('I was invoked without subcommand')121+ else:122+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")123+124+ @cli.command()125+ def sync():126+ click.echo('The subcommand')127+128+.. click:run::129+130+ invoke(cli, prog_name='tool', args=[])131+ invoke(cli, prog_name='tool', args=['sync'])132+133+134+135+Group Separation136+^^^^^^^^^^^^^^^^^^^137+Command :ref:`parameters` attached to a command belong only to that command.138+139+.. click:example::140+ @click.group()141+ def greeting():142+ pass143+144+ @greeting.command()145+ @click.option('--count', default=1)146+ def hello(count):147+ for x in range(count):148+ click.echo("Hello!")149+150+ @greeting.command()151+ @click.option('--count', default=1)152+ def goodbye(count):153+ for x in range(count):154+ click.echo("Goodbye!")155+156+.. click:run::157+158+ invoke(greeting, args=['hello', '--count', '2'])159+ invoke(greeting, args=['goodbye', '--count', '2'])160+ invoke(greeting)161+162+Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.163+164+This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165+166+- ``tool --help`` returns the help for the whole program (listing subcommands).167+- ``tool sub --help`` returns the help for the ``sub`` subcommand.168+- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.169+170+Arbitrary Nesting171+^^^^^^^^^^^^^^^^^^^172+:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.173+174+.. click:example::175+176+ @click.group()177+ def cli():178+ pass179+180+ # Not @click so that the group is registered now.181+ @cli.group()182+ def session():183+ click.echo('Starting session')184+185+ @session.command()186+ def initdb():187+ click.echo('Initialized the database')188+189+ @session.command()190+ def dropdb():191+ click.echo('Dropped the database')192+193+.. click:run::194+195+ invoke(cli, args=['session', 'initdb'])196+197+Lazily Attaching Commands198+^^^^^^^^^^^^^^^^^^^^^^^^^^^199+Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.200+201+.. click:example::202+203+ @click.group()204+ def cli():205+ pass206+207+ @cli.command()208+ def initdb():209+ click.echo('Initialized the database')210+211+ @click.command()212+ def dropdb():213+ click.echo('Dropped the database')214+215+ cli.add_command(dropdb)216+217+.. click:run::218+219+ invoke(cli, args=['initdb'])220+ invoke(cli, args=['dropdb'])221+222+Context Object223+-------------------224+The :class:`Context` object is how commands and groups communicate.225+226+Auto Envvar Prefix227+^^^^^^^^^^^^^^^^^^^^228+Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229+called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230+231+Example usage:232+233+.. click:example::234+235+ @click.command()236+ @click.option('--username')237+ def greet(username):238+ click.echo(f'Hello {username}!')239+240+ if __name__ == '__main__':241+ greet(auto_envvar_prefix='GREETER')242+243+And from the command line:244+245+.. click:run::246+247+ invoke(greet, env={'GREETER_USERNAME': 'john'},248+ auto_envvar_prefix='GREETER')249+250+When using ``auto_envvar_prefix`` with command groups, the command name251+needs to be included in the environment variable, between the prefix and252+the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253+subcommand called ``run-server`` taking an option called ``host`` and254+the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255+256+.. click:example::257+258+ @click.group()259+ @click.option('--debug/--no-debug')260+ def cli(debug):261+ click.echo(f"Debug mode is {'on' if debug else 'off'}")262+263+ @cli.command()264+ @click.option('--username')265+ def greet(username):266+ click.echo(f"Hello {username}!")267+268+ if __name__ == '__main__':269+ cli(auto_envvar_prefix='GREETER')270+271+.. click:run::272+273+ invoke(cli, args=['greet',],274+ env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275+ auto_envvar_prefix='GREETER')276+277+Global Context Access278+^^^^^^^^^^^^^^^^^^^^^^279+280+.. versionadded:: 5.0281+282+Starting with Click 5.0 it is possible to access the current context from283+anywhere within the same thread through the use of the284+:func:`get_current_context` function which returns it. This is primarily285+useful for accessing the context bound object as well as some flags that286+are stored on it to customize the runtime behavior. For instance the287+:func:`echo` function does this to infer the default value of the `color`288+flag.289+290+Example usage::291+292+ def get_current_command_name():293+ return click.get_current_context().info_name294+295+It should be noted that this only works within the current thread. If you296+spawn additional threads then those threads will not have the ability to297+refer to the current context. If you want to give another thread the298+ability to refer to this context you need to use the context within the299+thread as a context manager::300+301+ def spawn_thread(ctx, func):302+ def wrapper():303+ with ctx:304+ func()305+ t = threading.Thread(target=wrapper)306+ t.start()307+ return t308+309+Now the thread function can access the context like the main thread would310+do. However if you do use this for threading you need to be very careful311+as the vast majority of the context is not thread safe! You are only312+allowed to read from the context, but not to perform any modifications on313+it.314+315+316+Detecting the Source of a Parameter317+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318+319+In some situations it's helpful to understand whether or not an option320+or parameter came from the command line, the environment, the default321+value, or :attr:`Context.default_map`. The322+:meth:`Context.get_parameter_source` method can be used to find this323+out. It will return a member of the :class:`~click.core.ParameterSource`324+enum.325+326+.. click:example::327+328+ @click.command()329+ @click.argument('port', nargs=1, default=8080, envvar="PORT")330+ @click.pass_context331+ def cli(ctx, port):332+ source = ctx.get_parameter_source("port")333+ click.echo(f"Port came from {source.name}")334+335+.. click:run::336+337+ invoke(cli, prog_name='cli', args=['8080'])338+ println()339+ invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340+ println()341+ invoke(cli, prog_name='cli', args=[])342+ println()deleted:docs/commands-and-groups.rst-342 removed
1-Basic Commands, Groups, Context2-================================3-4-.. currentmodule:: click5-6-Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7-8-.. contents::9- :depth: 210- :local:11-12-Commands13---------------------14-15-Basic Command Example16-^^^^^^^^^^^^^^^^^^^^^^^17-A simple command decorator takes no arguments.18-19-.. click:example::20- @click.command()21- @click.option('--count', default=1)22- def hello(count):23- for x in range(count):24- click.echo("Hello!")25-26-.. click:run::27- invoke(hello, args=['--count', '2',])28-29-Renaming Commands30-^^^^^^^^^^^^^^^^^^^31-By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.32-33-.. click:example::34- @click.command('say-hello')35- @click.option('--count', default=1)36- def hello(count):37- for x in range(count):38- click.echo("Hello!")39-40-.. click:run::41- invoke(hello, args=['--count', '2',])42-43-Deprecating Commands44-^^^^^^^^^^^^^^^^^^^^^^45-To mark a command as deprecated pass in ``deprecated=True``46-47-.. click:example::48- @click.command('say-hello', deprecated=True)49- @click.option('--count', default=1)50- def hello(count):51- for x in range(count):52- click.echo("Hello!")53-54-.. click:run::55- invoke(hello, args=['--count', '2',])56-57-Groups58-------------59-60-Basic Group Example61-^^^^^^^^^^^^^^^^^^^^^62-A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.63-64-.. click:example::65- @click.group()66- def greeting():67- click.echo('Starting greeting ...')68-69- @greeting.command('say-hello')70- @click.option('--count', default=1)71- def hello(count):72- for x in range(count):73- click.echo("Hello!")74-75-At the top level:76-77-.. click:run::78-79- invoke(greeting)80-81-At the command level:82-83-.. click:run::84-85- invoke(greeting, args=['say-hello'])86- invoke(greeting, args=['say-hello', '--help'])87-88-As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).89-90-Renaming Groups91-^^^^^^^^^^^^^^^^^92-To have a name other than the decorated function name as the group name, pass it in as the first positional argument.93-94-.. click:example::95- @click.group('greet-someone')96- def greeting():97- click.echo('Starting greeting ...')98-99- @greeting.command('say-hello')100- @click.option('--count', default=1)101- def hello(count):102- for x in range(count):103- click.echo("Hello!")104-105-.. click:run::106-107- invoke(greeting, args=['say-hello'])108-109-Group Invocation Without Command110-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111-112-By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.113-114-.. click:example::115-116- @click.group(invoke_without_command=True)117- @click.pass_context118- def cli(ctx):119- if ctx.invoked_subcommand is None:120- click.echo('I was invoked without subcommand')121- else:122- click.echo(f"I am about to invoke {ctx.invoked_subcommand}")123-124- @cli.command()125- def sync():126- click.echo('The subcommand')127-128-.. click:run::129-130- invoke(cli, prog_name='tool', args=[])131- invoke(cli, prog_name='tool', args=['sync'])132-133-134-135-Group Separation136-^^^^^^^^^^^^^^^^^^^137-Command :ref:`parameters` attached to a command belong only to that command.138-139-.. click:example::140- @click.group()141- def greeting():142- pass143-144- @greeting.command()145- @click.option('--count', default=1)146- def hello(count):147- for x in range(count):148- click.echo("Hello!")149-150- @greeting.command()151- @click.option('--count', default=1)152- def goodbye(count):153- for x in range(count):154- click.echo("Goodbye!")155-156-.. click:run::157-158- invoke(greeting, args=['hello', '--count', '2'])159- invoke(greeting, args=['goodbye', '--count', '2'])160- invoke(greeting)161-162-Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.163-164-This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165-166-- ``tool --help`` returns the help for the whole program (listing subcommands).167-- ``tool sub --help`` returns the help for the ``sub`` subcommand.168-- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.169-170-Arbitrary Nesting171-^^^^^^^^^^^^^^^^^^^172-:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.173-174-.. click:example::175-176- @click.group()177- def cli():178- pass179-180- # Not @click so that the group is registered now.181- @cli.group()182- def session():183- click.echo('Starting session')184-185- @session.command()186- def initdb():187- click.echo('Initialized the database')188-189- @session.command()190- def dropdb():191- click.echo('Dropped the database')192-193-.. click:run::194-195- invoke(cli, args=['session', 'initdb'])196-197-Lazily Attaching Commands198-^^^^^^^^^^^^^^^^^^^^^^^^^^^199-Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.200-201-.. click:example::202-203- @click.group()204- def cli():205- pass206-207- @cli.command()208- def initdb():209- click.echo('Initialized the database')210-211- @click.command()212- def dropdb():213- click.echo('Dropped the database')214-215- cli.add_command(dropdb)216-217-.. click:run::218-219- invoke(cli, args=['initdb'])220- invoke(cli, args=['dropdb'])221-222-Context Object223--------------------224-The :class:`Context` object is how commands and groups communicate.225-226-Auto Envvar Prefix227-^^^^^^^^^^^^^^^^^^^^228-Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229-called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230-231-Example usage:232-233-.. click:example::234-235- @click.command()236- @click.option('--username')237- def greet(username):238- click.echo(f'Hello {username}!')239-240- if __name__ == '__main__':241- greet(auto_envvar_prefix='GREETER')242-243-And from the command line:244-245-.. click:run::246-247- invoke(greet, env={'GREETER_USERNAME': 'john'},248- auto_envvar_prefix='GREETER')249-250-When using ``auto_envvar_prefix`` with command groups, the command name251-needs to be included in the environment variable, between the prefix and252-the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253-subcommand called ``run-server`` taking an option called ``host`` and254-the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255-256-.. click:example::257-258- @click.group()259- @click.option('--debug/--no-debug')260- def cli(debug):261- click.echo(f"Debug mode is {'on' if debug else 'off'}")262-263- @cli.command()264- @click.option('--username')265- def greet(username):266- click.echo(f"Hello {username}!")267-268- if __name__ == '__main__':269- cli(auto_envvar_prefix='GREETER')270-271-.. click:run::272-273- invoke(cli, args=['greet',],274- env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275- auto_envvar_prefix='GREETER')276-277-Global Context Access278-^^^^^^^^^^^^^^^^^^^^^^279-280-.. versionadded:: 5.0281-282-Starting with Click 5.0 it is possible to access the current context from283-anywhere within the same thread through the use of the284-:func:`get_current_context` function which returns it. This is primarily285-useful for accessing the context bound object as well as some flags that286-are stored on it to customize the runtime behavior. For instance the287-:func:`echo` function does this to infer the default value of the `color`288-flag.289-290-Example usage::291-292- def get_current_command_name():293- return click.get_current_context().info_name294-295-It should be noted that this only works within the current thread. If you296-spawn additional threads then those threads will not have the ability to297-refer to the current context. If you want to give another thread the298-ability to refer to this context you need to use the context within the299-thread as a context manager::300-301- def spawn_thread(ctx, func):302- def wrapper():303- with ctx:304- func()305- t = threading.Thread(target=wrapper)306- t.start()307- return t308-309-Now the thread function can access the context like the main thread would310-do. However if you do use this for threading you need to be very careful311-as the vast majority of the context is not thread safe! You are only312-allowed to read from the context, but not to perform any modifications on313-it.314-315-316-Detecting the Source of a Parameter317-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318-319-In some situations it's helpful to understand whether or not an option320-or parameter came from the command line, the environment, the default321-value, or :attr:`Context.default_map`. The322-:meth:`Context.get_parameter_source` method can be used to find this323-out. It will return a member of the :class:`~click.core.ParameterSource`324-enum.325-326-.. click:example::327-328- @click.command()329- @click.argument('port', nargs=1, default=8080, envvar="PORT")330- @click.pass_context331- def cli(ctx, port):332- source = ctx.get_parameter_source("port")333- click.echo(f"Port came from {source.name}")334-335-.. click:run::336-337- invoke(cli, prog_name='cli', args=['8080'])338- println()339- invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340- println()341- invoke(cli, prog_name='cli', args=[])342- println()