Skip to content
Myr

commands-and-groups.md

This file

Path

docs/commands-and-groups.md

426 lines · 11.4 KiB · Markdown

Last changed by

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

History of this file

Take it

Show it rendered

1# Basic Commands, Groups, Context23```{currentmodule} click4```56Commands and Groups are the building blocks for Click applications.7{class}`Command` wraps a function to make it into a cli command. {class}`Group`8wraps Commands and Groups to make them into applications. {class}`Context` is9how groups and commands communicate.1011```{contents}12---13depth: 214local: true15---16```1718## Commands1920### Basic Command Example2122A simple command decorator takes no arguments.2324```{eval-rst}25.. click:example::2627    @click.command()28    @click.option('--count', default=1)29    def hello(count):30        for x in range(count):31            click.echo("Hello!")3233.. click:run::34    invoke(hello, args=['--count', '2',])35```3637### Renaming Commands3839By default the command is the function name with underscores replaced by dashes.40To change this pass the  desired name into the first positional argument.4142```{eval-rst}43.. click:example::4445    @click.command('say-hello')46    @click.option('--count', default=1)47    def hello(count):48        for x in range(count):49            click.echo("Hello!")5051.. click:run::52    invoke(hello, args=['--count', '2',])53```5455### Deprecating Commands5657To mark a command as deprecated pass in `deprecated=True`5859```{eval-rst}60.. click:example::6162    @click.command('say-hello', deprecated=True)63    @click.option('--count', default=1)64    def hello(count):65        for x in range(count):66            click.echo("Hello!")6768.. click:run::69    invoke(hello, args=['--count', '2',])70```7172## Groups7374### Basic Group Example7576A group wraps one or more commands. After being wrapped, the commands are nested77under that group. You can see that on the help pages and in the execution. By78default, invoking the group with no command shows the help page.7980```{eval-rst}81.. click:example::8283    @click.group()84    def greeting():85        click.echo('Starting greeting ...')8687    @greeting.command('say-hello')88    @click.option('--count', default=1)89    def hello(count):90        for x in range(count):91            click.echo("Hello!")9293At the top level:9495.. click:run::9697    invoke(greeting)9899At the command level:100101.. click:run::102103    invoke(greeting, args=['say-hello'])104    invoke(greeting, args=['say-hello', '--help'])105```106107As you can see from the above example, the function wrapped by the group108decorator executes unless it is interrupted (for example by calling the help).109110### Renaming Groups111112To have a name other than the decorated function name as the group name, pass it113in as the first positional argument.114115```{eval-rst}116.. click:example::117118    @click.group('greet-someone')119    def greeting():120        click.echo('Starting greeting ...')121122    @greeting.command('say-hello')123    @click.option('--count', default=1)124    def hello(count):125        for x in range(count):126            click.echo("Hello!")127128.. click:run::129130    invoke(greeting, args=['say-hello'])131```132133### Group Invocation Without Command134135By default, if a group is passed without a command, the group is not invoked and136a command automatically passes `--help`. To change this, pass137`invoke_without_command=True` to the group. The context object also includes138information about whether or not the group invocation would go to a command139nested under it.140141```{eval-rst}142.. click:example::143144    @click.group(invoke_without_command=True)145    @click.pass_context146    def cli(ctx):147        if ctx.invoked_subcommand is None:148            click.echo('I was invoked without subcommand')149        else:150            click.echo(f"I am about to invoke {ctx.invoked_subcommand}")151152    @cli.command()153    def sync():154        click.echo('The subcommand')155156.. click:run::157158    invoke(cli, prog_name='tool', args=[])159    invoke(cli, prog_name='tool', args=['sync'])160```161162### Group Separation163164Command {ref}`parameters` attached to a command belong only to that command.165166```{eval-rst}167.. click:example::168169    @click.group()170    def greeting():171        pass172173    @greeting.command()174    @click.option('--count', default=1)175    def hello(count):176        for x in range(count):177            click.echo("Hello!")178179    @greeting.command()180    @click.option('--count', default=1)181    def goodbye(count):182        for x in range(count):183            click.echo("Goodbye!")184185.. click:run::186187    invoke(greeting, args=['hello', '--count', '2'])188    invoke(greeting, args=['goodbye', '--count', '2'])189    invoke(greeting)190```191192Additionally parameters for a given group belong only to that group and not to193the commands under it. What this means is that options and arguments for a194specific command have to be specified *after* the command name itself, but195*before* any other command names.196197This behavior is observable with the `--help` option. Suppose we have a group198called `tool` containing a command called `sub`.199200- `tool --help` returns the help for the whole program (listing subcommands).201- `tool sub --help` returns the help for the `sub` subcommand.202- But `tool --help sub` treats `--help` as an argument for the main program.203  Click then invokes the callback for `--help`, which prints the help and aborts204  the program before click can process the subcommand.205206### Arbitrary Nesting207208{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.209210```{eval-rst}211.. click:example::212213    @click.group()214    def cli():215        pass216217    # Not @click so that the group is registered now.218    @cli.group()219    def session():220        click.echo('Starting session')221222    @session.command()223    def initdb():224        click.echo('Initialized the database')225226    @session.command()227    def dropdb():228        click.echo('Dropped the database')229230.. click:run::231232    invoke(cli, args=['session', 'initdb'])233```234235### Lazily Attaching Commands236237Most examples so far have attached the commands to a group immediately, but238commands may be registered later. This could be used to split commands into239multiple Python modules. Regardless of how they are attached, the commands are240invoked identically.241242```{eval-rst}243.. click:example::244245    @click.group()246    def cli():247        pass248249    @cli.command()250    def initdb():251        click.echo('Initialized the database')252253    @click.command()254    def dropdb():255        click.echo('Dropped the database')256257    cli.add_command(dropdb)258259.. click:run::260261    invoke(cli, args=['initdb'])262    invoke(cli, args=['dropdb'])263```264265## Context Object266The {class}`Context` object is how commands and groups communicate.267268### Auto Envvar Prefix269270Automatically built environment variables are supported for options only. To271enable this feature, the `auto_envvar_prefix` parameter needs to be passed to272the script that is invoked.  Each command and parameter is then added as an273uppercase underscore-separated variable.  If you have a subcommand274called `run` taking an option called `reload` and the prefix is `WEB`, then the275variable is `WEB_RUN_RELOAD`.276277Example usage:278279```{eval-rst}280.. click:example::281282    @click.command()283    @click.option('--username')284    def greet(username):285        click.echo(f'Hello {username}!')286287    if __name__ == '__main__':288        greet(auto_envvar_prefix='GREETER')289290And from the command line:291292.. click:run::293294    invoke(greet, env={'GREETER_USERNAME': 'john'},295           auto_envvar_prefix='GREETER')296```297298When using `auto_envvar_prefix` with command groups, the command name299needs to be included in the environment variable, between the prefix and300the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a301subcommand called `run-server` taking an option called `host` and302the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.303304```{eval-rst}305.. click:example::306307   @click.group()308   @click.option('--debug/--no-debug')309   def cli(debug):310       click.echo(f"Debug mode is {'on' if debug else 'off'}")311312   @cli.command()313   @click.option('--username')314   def greet(username):315       click.echo(f"Hello {username}!")316317   if __name__ == '__main__':318       cli(auto_envvar_prefix='GREETER')319320.. click:run::321322   invoke(cli, args=['greet',],323          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},324          auto_envvar_prefix='GREETER')325```326327### Global Context Access328329```{versionadded} 5.0330```331332Starting with Click 5.0 it is possible to access the current context from333anywhere within the same thread through the use of the334{func}`get_current_context` function which returns it.  This is primarily335useful for accessing the context bound object as well as some flags that336are stored on it to customize the runtime behavior.  For instance the337{func}`echo` function does this to infer the default value of the `color`338flag.339340Example usage:341342```python343    def get_current_command_name():344        return click.get_current_context().info_name345```346347It should be noted that this only works within the current thread.  If you348spawn additional threads then those threads will not have the ability to349refer to the current context.  If you want to give another thread the350ability to refer to this context you need to use the context within the351thread as a context manager:352353```python354    def spawn_thread(ctx, func):355        def wrapper():356            with ctx:357                func()358        t = threading.Thread(target=wrapper)359        t.start()360        return t361```362363Now the thread function can access the context like the main thread would364do.  However if you do use this for threading you need to be very careful365as the vast majority of the context is not thread safe!  You are only366allowed to read from the context, but not to perform any modifications on367it.368369370### Parameter Source Priority371372When a parameter's value is resolved, Click checks several sources373in the following order of precedence:3743751.  **Prompt** (`PROMPT`): interactively provided by the user at a prompt.3762.  **Command line** (`COMMANDLINE`): provided as a CLI argument or option.3773.  **Environment variable** (`ENVIRONMENT`): read from an environment variable.3784.  **Default map** (`DEFAULT_MAP`): looked up from {attr}`Context.default_map`.3795.  **Default** (`DEFAULT`): the default value defined on the parameter.380381{class}`~click.core.ParameterSource` members are ordered from most382explicit to least explicit. Because it is an {class}`~enum.IntEnum`,383you can use comparison operators to check how explicitly a value was384provided:385386```python387source = ctx.get_parameter_source("port")388389# True if the value was explicitly set (command line, prompt, or env var).390if source < click.ParameterSource.DEFAULT_MAP:391    ...392393# True if the value came from any kind of default.394if source >= click.ParameterSource.DEFAULT_MAP:395    ...396```397398399### Detecting the Source of a Parameter400401In some situations it's helpful to understand whether or not an option402or parameter came from the command line, the environment, the default403value, or {attr}`Context.default_map`. The404{meth}`Context.get_parameter_source` method can be used to find this405out. It will return a member of the {class}`~click.core.ParameterSource`406enum.407408```{eval-rst}409.. click:example::410411    @click.command()412    @click.argument('port', nargs=1, default=8080, envvar="PORT")413    @click.pass_context414    def cli(ctx, port):415        source = ctx.get_parameter_source("port")416        click.echo(f"Port came from {source.name}")417418.. click:run::419420    invoke(cli, prog_name='cli', args=['8080'])421    println()422    invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})423    println()424    invoke(cli, prog_name='cli', args=[])425    println()426```