Skip to content
Myr

Merge branch 'stable' into show-default-string-in-prompt

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

authored by Rowlando13 · committed by GitHub · parents 39413d9, 8c95c73 · Browse files · 15 files+1265 added−792 removed
This commit

State

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

Diff stats

15 files+1265 added−792 removed

  • tests:+70 added−5 removed
  • other:+1195 added−787 removed

15 files+1265 added−792 removed

added:docs/commands-and-groups.md+372 added
1# Basic Commands, Groups, Context23```{currentmodule} click4```56Commands 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.78```{contents}9---10depth: 211local: true12---13```1415## Commands1617### Basic Command Example1819A simple command decorator takes no arguments.2021```{eval-rst}22.. click:example::2324 @click.command()25 @click.option('--count', default=1)26 def hello(count):27 for x in range(count):28 click.echo("Hello!")2930.. click:run::31 invoke(hello, args=['--count', '2',])32```3334### Renaming Commands3536By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.3738```{eval-rst}39.. click:example::4041 @click.command('say-hello')42 @click.option('--count', default=1)43 def hello(count):44 for x in range(count):45 click.echo("Hello!")4647.. click:run::48 invoke(hello, args=['--count', '2',])49```5051### Deprecating Commands5253To mark a command as deprecated pass in `deprecated=True`5455```{eval-rst}56.. click:example::5758 @click.command('say-hello', deprecated=True)59 @click.option('--count', default=1)60 def hello(count):61 for x in range(count):62 click.echo("Hello!")6364.. click:run::65 invoke(hello, args=['--count', '2',])66```6768## Groups6970### Basic Group Example7172A 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.7374```{eval-rst}75.. click:example::7677 @click.group()78 def greeting():79 click.echo('Starting greeting ...')8081 @greeting.command('say-hello')82 @click.option('--count', default=1)83 def hello(count):84 for x in range(count):85 click.echo("Hello!")8687At the top level:8889.. click:run::9091 invoke(greeting)9293At the command level:9495.. click:run::9697 invoke(greeting, args=['say-hello'])98 invoke(greeting, args=['say-hello', '--help'])99```100101As 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).102103### Renaming Groups104105To have a name other than the decorated function name as the group name, pass it in as the first positional argument.106107```{eval-rst}108.. click:example::109110 @click.group('greet-someone')111 def greeting():112 click.echo('Starting greeting ...')113114 @greeting.command('say-hello')115 @click.option('--count', default=1)116 def hello(count):117 for x in range(count):118 click.echo("Hello!")119120.. click:run::121122 invoke(greeting, args=['say-hello'])123```124125### Group Invocation Without Command126127By 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.128129```{eval-rst}130.. click:example::131132 @click.group(invoke_without_command=True)133 @click.pass_context134 def cli(ctx):135 if ctx.invoked_subcommand is None:136 click.echo('I was invoked without subcommand')137 else:138 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")139140 @cli.command()141 def sync():142 click.echo('The subcommand')143144.. click:run::145146 invoke(cli, prog_name='tool', args=[])147 invoke(cli, prog_name='tool', args=['sync'])148```149150### Group Separation151152Command {ref}`parameters` attached to a command belong only to that command.153154```{eval-rst}155.. click:example::156157 @click.group()158 def greeting():159 pass160161 @greeting.command()162 @click.option('--count', default=1)163 def hello(count):164 for x in range(count):165 click.echo("Hello!")166167 @greeting.command()168 @click.option('--count', default=1)169 def goodbye(count):170 for x in range(count):171 click.echo("Goodbye!")172173.. click:run::174175 invoke(greeting, args=['hello', '--count', '2'])176 invoke(greeting, args=['goodbye', '--count', '2'])177 invoke(greeting)178```179180Additionally 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.181182This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.183184- `tool --help` returns the help for the whole program (listing subcommands).185- `tool sub --help` returns the help for the `sub` subcommand.186- 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.187188### Arbitrary Nesting189190{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.191192```{eval-rst}193.. click:example::194195 @click.group()196 def cli():197 pass198199 # Not @click so that the group is registered now.200 @cli.group()201 def session():202 click.echo('Starting session')203204 @session.command()205 def initdb():206 click.echo('Initialized the database')207208 @session.command()209 def dropdb():210 click.echo('Dropped the database')211212.. click:run::213214 invoke(cli, args=['session', 'initdb'])215```216217### Lazily Attaching Commands218219Most 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.220221```{eval-rst}222.. click:example::223224 @click.group()225 def cli():226 pass227228 @cli.command()229 def initdb():230 click.echo('Initialized the database')231232 @click.command()233 def dropdb():234 click.echo('Dropped the database')235236 cli.add_command(dropdb)237238.. click:run::239240 invoke(cli, args=['initdb'])241 invoke(cli, args=['dropdb'])242```243244## Context Object245The {class}`Context` object is how commands and groups communicate.246247### Auto Envvar Prefix248249Automatically 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 subcommand250called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.251252Example usage:253254```{eval-rst}255.. click:example::256257 @click.command()258 @click.option('--username')259 def greet(username):260 click.echo(f'Hello {username}!')261262 if __name__ == '__main__':263 greet(auto_envvar_prefix='GREETER')264265And from the command line:266267.. click:run::268269 invoke(greet, env={'GREETER_USERNAME': 'john'},270 auto_envvar_prefix='GREETER')271```272273When using `auto_envvar_prefix` with command groups, the command name274needs to be included in the environment variable, between the prefix and275the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a276subcommand called `run-server` taking an option called `host` and277the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.278279```{eval-rst}280.. click:example::281282 @click.group()283 @click.option('--debug/--no-debug')284 def cli(debug):285 click.echo(f"Debug mode is {'on' if debug else 'off'}")286287 @cli.command()288 @click.option('--username')289 def greet(username):290 click.echo(f"Hello {username}!")291292 if __name__ == '__main__':293 cli(auto_envvar_prefix='GREETER')294295.. click:run::296297 invoke(cli, args=['greet',],298 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},299 auto_envvar_prefix='GREETER')300```301302### Global Context Access303304```{versionadded} 5.0305```306307Starting with Click 5.0 it is possible to access the current context from308anywhere within the same thread through the use of the309{func}`get_current_context` function which returns it. This is primarily310useful for accessing the context bound object as well as some flags that311are stored on it to customize the runtime behavior. For instance the312{func}`echo` function does this to infer the default value of the `color`313flag.314315Example usage:316317```python318 def get_current_command_name():319 return click.get_current_context().info_name320```321322It should be noted that this only works within the current thread. If you323spawn additional threads then those threads will not have the ability to324refer to the current context. If you want to give another thread the325ability to refer to this context you need to use the context within the326thread as a context manager:327328```python329 def spawn_thread(ctx, func):330 def wrapper():331 with ctx:332 func()333 t = threading.Thread(target=wrapper)334 t.start()335 return t336```337338Now the thread function can access the context like the main thread would339do. However if you do use this for threading you need to be very careful340as the vast majority of the context is not thread safe! You are only341allowed to read from the context, but not to perform any modifications on342it.343344345### Detecting the Source of a Parameter346347In some situations it's helpful to understand whether or not an option348or parameter came from the command line, the environment, the default349value, or {attr}`Context.default_map`. The350{meth}`Context.get_parameter_source` method can be used to find this351out. It will return a member of the {class}`~click.core.ParameterSource`352enum.353354```{eval-rst}355.. click:example::356357 @click.command()358 @click.argument('port', nargs=1, default=8080, envvar="PORT")359 @click.pass_context360 def cli(ctx, port):361 source = ctx.get_parameter_source("port")362 click.echo(f"Port came from {source.name}")363364.. click:run::365366 invoke(cli, prog_name='cli', args=['8080'])367 println()368 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})369 println()370 invoke(cli, prog_name='cli', args=[])371 println()372```
deleted:docs/commands-and-groups.rst-342 removed
1Basic Commands, Groups, Context2================================34.. currentmodule:: click56Commands 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.78.. contents::9 :depth: 210 :local:1112Commands13--------------------1415Basic Command Example16^^^^^^^^^^^^^^^^^^^^^^^17A simple command decorator takes no arguments.1819.. 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!")2526.. click:run::27 invoke(hello, args=['--count', '2',])2829Renaming Commands30^^^^^^^^^^^^^^^^^^^31By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.3233.. 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!")3940.. click:run::41 invoke(hello, args=['--count', '2',])4243Deprecating Commands44^^^^^^^^^^^^^^^^^^^^^^45To mark a command as deprecated pass in ``deprecated=True``4647.. 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!")5354.. click:run::55 invoke(hello, args=['--count', '2',])5657Groups58------------5960Basic Group Example61^^^^^^^^^^^^^^^^^^^^^62A 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.6364.. click:example::65 @click.group()66 def greeting():67 click.echo('Starting greeting ...')6869 @greeting.command('say-hello')70 @click.option('--count', default=1)71 def hello(count):72 for x in range(count):73 click.echo("Hello!")7475At the top level:7677.. click:run::7879 invoke(greeting)8081At the command level:8283.. click:run::8485 invoke(greeting, args=['say-hello'])86 invoke(greeting, args=['say-hello', '--help'])8788As 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).8990Renaming Groups91^^^^^^^^^^^^^^^^^92To have a name other than the decorated function name as the group name, pass it in as the first positional argument.9394.. click:example::95 @click.group('greet-someone')96 def greeting():97 click.echo('Starting greeting ...')9899 @greeting.command('say-hello')100 @click.option('--count', default=1)101 def hello(count):102 for x in range(count):103 click.echo("Hello!")104105.. click:run::106107 invoke(greeting, args=['say-hello'])108109Group Invocation Without Command110^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111112By 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.113114.. click:example::115116 @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}")123124 @cli.command()125 def sync():126 click.echo('The subcommand')127128.. click:run::129130 invoke(cli, prog_name='tool', args=[])131 invoke(cli, prog_name='tool', args=['sync'])132133134135Group Separation136^^^^^^^^^^^^^^^^^^^137Command :ref:`parameters` attached to a command belong only to that command.138139.. click:example::140 @click.group()141 def greeting():142 pass143144 @greeting.command()145 @click.option('--count', default=1)146 def hello(count):147 for x in range(count):148 click.echo("Hello!")149150 @greeting.command()151 @click.option('--count', default=1)152 def goodbye(count):153 for x in range(count):154 click.echo("Goodbye!")155156.. click:run::157158 invoke(greeting, args=['hello', '--count', '2'])159 invoke(greeting, args=['goodbye', '--count', '2'])160 invoke(greeting)161162Additionally 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.163164This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165166- ``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.169170Arbitrary 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.173174.. click:example::175176 @click.group()177 def cli():178 pass179180 # Not @click so that the group is registered now.181 @cli.group()182 def session():183 click.echo('Starting session')184185 @session.command()186 def initdb():187 click.echo('Initialized the database')188189 @session.command()190 def dropdb():191 click.echo('Dropped the database')192193.. click:run::194195 invoke(cli, args=['session', 'initdb'])196197Lazily Attaching Commands198^^^^^^^^^^^^^^^^^^^^^^^^^^^199Most 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.200201.. click:example::202203 @click.group()204 def cli():205 pass206207 @cli.command()208 def initdb():209 click.echo('Initialized the database')210211 @click.command()212 def dropdb():213 click.echo('Dropped the database')214215 cli.add_command(dropdb)216217.. click:run::218219 invoke(cli, args=['initdb'])220 invoke(cli, args=['dropdb'])221222Context Object223-------------------224The :class:`Context` object is how commands and groups communicate.225226Auto Envvar Prefix227^^^^^^^^^^^^^^^^^^^^228Automatically 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 subcommand229called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230231Example usage:232233.. click:example::234235 @click.command()236 @click.option('--username')237 def greet(username):238 click.echo(f'Hello {username}!')239240 if __name__ == '__main__':241 greet(auto_envvar_prefix='GREETER')242243And from the command line:244245.. click:run::246247 invoke(greet, env={'GREETER_USERNAME': 'john'},248 auto_envvar_prefix='GREETER')249250When using ``auto_envvar_prefix`` with command groups, the command name251needs to be included in the environment variable, between the prefix and252the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253subcommand called ``run-server`` taking an option called ``host`` and254the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255256.. click:example::257258 @click.group()259 @click.option('--debug/--no-debug')260 def cli(debug):261 click.echo(f"Debug mode is {'on' if debug else 'off'}")262263 @cli.command()264 @click.option('--username')265 def greet(username):266 click.echo(f"Hello {username}!")267268 if __name__ == '__main__':269 cli(auto_envvar_prefix='GREETER')270271.. click:run::272273 invoke(cli, args=['greet',],274 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275 auto_envvar_prefix='GREETER')276277Global Context Access278^^^^^^^^^^^^^^^^^^^^^^279280.. versionadded:: 5.0281282Starting with Click 5.0 it is possible to access the current context from283anywhere within the same thread through the use of the284:func:`get_current_context` function which returns it. This is primarily285useful for accessing the context bound object as well as some flags that286are stored on it to customize the runtime behavior. For instance the287:func:`echo` function does this to infer the default value of the `color`288flag.289290Example usage::291292 def get_current_command_name():293 return click.get_current_context().info_name294295It should be noted that this only works within the current thread. If you296spawn additional threads then those threads will not have the ability to297refer to the current context. If you want to give another thread the298ability to refer to this context you need to use the context within the299thread as a context manager::300301 def spawn_thread(ctx, func):302 def wrapper():303 with ctx:304 func()305 t = threading.Thread(target=wrapper)306 t.start()307 return t308309Now the thread function can access the context like the main thread would310do. However if you do use this for threading you need to be very careful311as the vast majority of the context is not thread safe! You are only312allowed to read from the context, but not to perform any modifications on313it.314315316Detecting the Source of a Parameter317^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318319In some situations it's helpful to understand whether or not an option320or parameter came from the command line, the environment, the default321value, or :attr:`Context.default_map`. The322:meth:`Context.get_parameter_source` method can be used to find this323out. It will return a member of the :class:`~click.core.ParameterSource`324enum.325326.. click:example::327328 @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}")334335.. click:run::336337 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()
added:docs/commands.md+437 added
1# Advanced Groups and Context23```{currentmodule} click4```56In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.78```{contents}9---10depth: 111local: true12---13```1415## Callback Invocation1617For a regular command, the callback is executed whenever the command runs.18If the script is the only command, it will always fire (unless a parameter19callback prevents it. This for instance happens if someone passes20`--help` to the script).2122For groups, the situation looks different. In this case, the callback fires23whenever a subcommand fires. What this means in practice is that an outer24command runs when an inner command runs:2526```{eval-rst}27.. click:example::2829 @click.group()30 @click.option('--debug/--no-debug', default=False)31 def cli(debug):32 click.echo(f"Debug mode is {'on' if debug else 'off'}")3334 @cli.command() # @cli, not @click!35 def sync():36 click.echo('Syncing')3738Here is what this looks like:3940.. click:run::4142 invoke(cli, prog_name='tool.py')43 println()44 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])45```4647## Nested Handling and Contexts4849As you can see from the earlier example, the basic command group accepts a50debug argument which is passed to its callback, but not to the sync51command itself. The sync command only accepts its own arguments.5253This allows tools to act completely independent of each other, but how54does one command talk to a nested one? The answer to this is the55{class}`Context`.5657Each time a command is invoked, a new context is created and linked with the58parent context. Normally, you can't see these contexts, but they are59there. Contexts are passed to parameter callbacks together with the60value automatically. Commands can also ask for the context to be passed61by marking themselves with the {func}`pass_context` decorator. In that62case, the context is passed as first argument.6364The context can also carry a program specified object that can be65used for the program's purposes. What this means is that you can build a66script like this:6768```{eval-rst}69.. click:example::7071 @click.group()72 @click.option('--debug/--no-debug', default=False)73 @click.pass_context74 def cli(ctx, debug):75 # ensure that ctx.obj exists and is a dict (in case `cli()` is called76 # by means other than the `if` block below)77 ctx.ensure_object(dict)7879 ctx.obj['DEBUG'] = debug8081 @cli.command()82 @click.pass_context83 def sync(ctx):84 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")8586 if __name__ == '__main__':87 cli(obj={})88```8990If the object is provided, each context will pass the object onwards to91its children, but at any level a context's object can be overridden. To92reach to a parent, `context.parent` can be used.9394In addition to that, instead of passing an object down, nothing stops the95application from modifying global state. For instance, you could just flip96a global `DEBUG` variable and be done with it.9798## Decorating Commands99100As you have seen in the earlier example, a decorator can change how a101command is invoked. What actually happens behind the scenes is that102callbacks are always invoked through the {meth}`Context.invoke` method103which automatically invokes a command correctly (by either passing the104context or not).105106This is very useful when you want to write custom decorators. For107instance, a common pattern would be to configure an object representing108state and then storing it on the context and then to use a custom109decorator to find the most recent object of this sort and pass it as first110argument.111112For instance, the {func}`pass_obj` decorator can be implemented like this:113114```{eval-rst}115.. click:example::116117 from functools import update_wrapper118119 def pass_obj(f):120 @click.pass_context121 def new_func(ctx, *args, **kwargs):122 return ctx.invoke(f, ctx.obj, *args, **kwargs)123 return update_wrapper(new_func, f)124```125126The {meth}`Context.invoke` command will automatically invoke the function127in the correct way, so the function will either be called with`f(ctx,128obj)` or `f(obj)` depending on whether or not it itself is decorated with129{func}`pass_context`.130131This is a very powerful concept that can be used to build very complex132nested applications; see {ref}`complex-guide` for more information.133134(command-chaining)=135136## Command Chaining137138It is useful to invoke more than one subcommand in one call. For example,139`my-app validate build upload` would invoke `validate`, then `build`, then140`upload`. To implement this, pass `chain=True` when creating a group.141142```{eval-rst}143.. click:example::144145 @click.group(chain=True)146 def cli():147 pass148149 @cli.command('validate')150 def validate():151 click.echo('validate')152153 @cli.command('build')154 def build():155 click.echo('build')156157You can invoke it like this:158159.. click:run::160161 invoke(cli, prog_name='my-app', args=['validate', 'build'])162```163164When using chaining, there are a few restrictions:165166- Only the last command may use `nargs=-1` on an argument, otherwise the167 parser will not be able to find further commands.168- It is not possible to nest groups below a chain group.169- On the command line, options must be specified before arguments for each170 command in the chain.171- The {attr}`Context.invoked_subcommand` attribute will be `'*'` because the172 parser doesn't know the full list of commands that will run yet.173174(command-pipelines)=175176## Command Pipelines177178When using chaining, a common pattern is to have each command process the179result of the previous command.180181A straightforward way to do this is to use {func}`make_pass_decorator` to pass182a context object to each command, and store and read the data on that object.183184```{eval-rst}185.. click:example::186187 pass_ns = click.make_pass_decorator(dict, ensure=True)188189 @click.group(chain=True)190 @click.argument("name")191 @pass_ns192 def cli(ns, name):193 ns["name"] = name194195 @cli.command196 @pass_ns197 def lower(ns):198 ns["name"] = ns["name"].lower()199200 @cli.command201 @pass_ns202 def show(ns):203 click.echo(ns["name"])204205.. click:run::206207 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])208```209210Another way to do this is to collect data returned by each command, then process211it at the end of the chain. Use the group's {meth}`~Group.result_callback`212decorator to register a function that is called after the chain is finished. It213is passed the list of return values as well as any parameters registered on the214group.215216A command can return anything, including a function. Here's an example of that,217where each subcommand creates a function that processes the input, then the218result callback calls each function. The command takes a file, processes each219line, then outputs it. If no subcommands are given, it outputs the contents220of the file unchanged.221222```python223@click.group(chain=True, invoke_without_command=True)224@click.argument("fin", type=click.File("r"))225def cli(fin):226 pass227228@cli.result_callback()229def process_pipeline(processors, fin):230 iterator = (x.rstrip("\r\n") for x in input)231232 for processor in processors:233 iterator = processor(iterator)234235 for item in iterator:236 click.echo(item)237238@cli.command("upper")239def make_uppercase():240 def processor(iterator):241 for line in iterator:242 yield line.upper()243 return processor244245@cli.command("lower")246def make_lowercase():247 def processor(iterator):248 for line in iterator:249 yield line.lower()250 return processor251252@cli.command("strip")253def make_strip():254 def processor(iterator):255 for line in iterator:256 yield line.strip()257 return processor258```259260That's a lot in one go, so let's go through it step by step.2612621. The first thing is to make a {func}`group` that is chainable. In263 addition to that we also instruct Click to invoke even if no264 subcommand is defined. If this would not be done, then invoking an265 empty pipeline would produce the help page instead of running the266 result callbacks.2672. The next thing we do is to register a result callback on our group.268 This callback will be invoked with an argument which is the list of269 all return values of all subcommands and then the same keyword270 parameters as our group itself. This means we can access the input271 file easily there without having to use the context object.2723. In this result callback we create an iterator of all the lines in the273 input file and then pass this iterator through all the returned274 callbacks from all subcommands and finally we print all lines to275 stdout.276277After that point we can register as many subcommands as we want and each278subcommand can return a processor function to modify the stream of lines.279280One important thing of note is that Click shuts down the context after281each callback has been run. This means that for instance file types282cannot be accessed in the `processor` functions as the files will already283be closed there. This limitation is unlikely to change because it would284make resource handling much more complicated. For such it's recommended285to not use the file type and manually open the file through286{func}`open_file`.287288For a more complex example that also improves upon handling of the pipelines,289see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe)290in the Click repository. It implements a pipeline based image editing tool291that has a nice internal structure.292293## Overriding Defaults294295By default, the default value for a parameter is pulled from the296`default` flag that is provided when it's defined, but that's not the297only place defaults can be loaded from. The other place is the298{attr}`Context.default_map` (a dictionary) on the context. This allows299defaults to be loaded from a configuration file to override the regular300defaults.301302This is useful if you plug in some commands from another package but303you're not satisfied with the defaults.304305The default map can be nested arbitrarily for each subcommand:306307```python308309 default_map = {310 "debug": True, # default for a top level option311 "runserver": {"port": 5000} # default for a subcommand312 }313```314315The default map can be provided when the script is invoked, or316overridden at any point by commands. For instance, a top-level command317could load the defaults from a configuration file.318319Example usage:320321```{eval-rst}322.. click:example::323324 import click325326 @click.group()327 def cli():328 pass329330 @cli.command()331 @click.option('--port', default=8000)332 def runserver(port):333 click.echo(f"Serving on http://127.0.0.1:{port}/")334335 if __name__ == '__main__':336 cli(default_map={337 'runserver': {338 'port': 5000339 }340 })341342And in action:343344.. click:run::345346 invoke(cli, prog_name='cli', args=['runserver'], default_map={347 'runserver': {348 'port': 5000349 }350 })351```352353## Context Defaults354355```{versionadded} 2.0356```357358Starting with Click 2.0 you can override defaults for contexts not just359when calling your script, but also in the decorator that declares a360command. For instance given the previous example which defines a custom361`default_map` this can also be accomplished in the decorator now.362363This example does the same as the previous example:364365```{eval-rst}366.. click:example::367368 import click369370 CONTEXT_SETTINGS = dict(371 default_map={'runserver': {'port': 5000}}372 )373374 @click.group(context_settings=CONTEXT_SETTINGS)375 def cli():376 pass377378 @cli.command()379 @click.option('--port', default=8000)380 def runserver(port):381 click.echo(f"Serving on http://127.0.0.1:{port}/")382383 if __name__ == '__main__':384 cli()385386And again the example in action:387388.. click:run::389390 invoke(cli, prog_name='cli', args=['runserver'])391```392393## Command Return Values394395```{versionadded} 3.0396```397398One of the new introductions in Click 3.0 is the full support for return399values from command callbacks. This enables a whole range of features400that were previously hard to implement.401402In essence any command callback can now return a value. This return value403is bubbled to certain receivers. One usecase for this has already been404show in the example of {ref}`command-chaining` where it has been405demonstrated that chained groups can have callbacks that process406all return values.407408When working with command return values in Click, this is what you need to409know:410411- The return value of a command callback is generally returned from the412 {meth}`Command.invoke` method. The exception to this rule has to413 do with {class}`Group`s:414415 - In a group the return value is generally the return value of the416 subcommand invoked. The only exception to this rule is that the417 return value is the return value of the group callback if it's418 invoked without arguments and `invoke_without_command` is enabled.419 - If a group is set up for chaining then the return value is a list420 of all subcommands' results.421 - Return values of groups can be processed through a422 {attr}`Group.result_callback`. This is invoked with the423 list of all return values in chain mode, or the single return424 value in case of non chained commands.425426- The return value is bubbled through from the {meth}`Context.invoke`427 and {meth}`Context.forward` methods. This is useful in situations428 where you internally want to call into another command.429430- Click does not have any hard requirements for the return values and431 does not use them itself. This allows return values to be used for432 custom decorators or workflows (like in the command chaining433 example).434435- When a Click script is invoked as command line application (through436 {meth}`Command.main`) the return value is ignored unless the437 `standalone_mode` is disabled in which case it's bubbled through.
deleted:docs/commands.rst-428 removed
1Advanced Groups and Context2=============================34.. currentmodule:: click56In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.78.. contents::9 :depth: 110 :local:1112Callback Invocation13-------------------1415For a regular command, the callback is executed whenever the command runs.16If the script is the only command, it will always fire (unless a parameter17callback prevents it. This for instance happens if someone passes18``--help`` to the script).1920For groups, the situation looks different. In this case, the callback fires21whenever a subcommand fires. What this means in practice is that an outer22command runs when an inner command runs:2324.. click:example::2526 @click.group()27 @click.option('--debug/--no-debug', default=False)28 def cli(debug):29 click.echo(f"Debug mode is {'on' if debug else 'off'}")3031 @cli.command() # @cli, not @click!32 def sync():33 click.echo('Syncing')3435Here is what this looks like:3637.. click:run::3839 invoke(cli, prog_name='tool.py')40 println()41 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])4243Nested Handling and Contexts44----------------------------4546As you can see from the earlier example, the basic command group accepts a47debug argument which is passed to its callback, but not to the sync48command itself. The sync command only accepts its own arguments.4950This allows tools to act completely independent of each other, but how51does one command talk to a nested one? The answer to this is the52:class:`Context`.5354Each time a command is invoked, a new context is created and linked with the55parent context. Normally, you can't see these contexts, but they are56there. Contexts are passed to parameter callbacks together with the57value automatically. Commands can also ask for the context to be passed58by marking themselves with the :func:`pass_context` decorator. In that59case, the context is passed as first argument.6061The context can also carry a program specified object that can be62used for the program's purposes. What this means is that you can build a63script like this:6465.. click:example::6667 @click.group()68 @click.option('--debug/--no-debug', default=False)69 @click.pass_context70 def cli(ctx, debug):71 # ensure that ctx.obj exists and is a dict (in case `cli()` is called72 # by means other than the `if` block below)73 ctx.ensure_object(dict)7475 ctx.obj['DEBUG'] = debug7677 @cli.command()78 @click.pass_context79 def sync(ctx):80 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")8182 if __name__ == '__main__':83 cli(obj={})8485If the object is provided, each context will pass the object onwards to86its children, but at any level a context's object can be overridden. To87reach to a parent, ``context.parent`` can be used.8889In addition to that, instead of passing an object down, nothing stops the90application from modifying global state. For instance, you could just flip91a global ``DEBUG`` variable and be done with it.9293Decorating Commands94-------------------9596As you have seen in the earlier example, a decorator can change how a97command is invoked. What actually happens behind the scenes is that98callbacks are always invoked through the :meth:`Context.invoke` method99which automatically invokes a command correctly (by either passing the100context or not).101102This is very useful when you want to write custom decorators. For103instance, a common pattern would be to configure an object representing104state and then storing it on the context and then to use a custom105decorator to find the most recent object of this sort and pass it as first106argument.107108For instance, the :func:`pass_obj` decorator can be implemented like this:109110.. click:example::111112 from functools import update_wrapper113114 def pass_obj(f):115 @click.pass_context116 def new_func(ctx, *args, **kwargs):117 return ctx.invoke(f, ctx.obj, *args, **kwargs)118 return update_wrapper(new_func, f)119120The :meth:`Context.invoke` command will automatically invoke the function121in the correct way, so the function will either be called with ``f(ctx,122obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with123:func:`pass_context`.124125This is a very powerful concept that can be used to build very complex126nested applications; see :ref:`complex-guide` for more information.127128.. _command-chaining:129130Command Chaining131----------------132133It is useful to invoke more than one subcommand in one call. For example,134``my-app validate build upload`` would invoke ``validate``, then ``build``, then135``upload``. To implement this, pass ``chain=True`` when creating a group.136137.. click:example::138139 @click.group(chain=True)140 def cli():141 pass142143 @cli.command('validate')144 def validate():145 click.echo('validate')146147 @cli.command('build')148 def build():149 click.echo('build')150151You can invoke it like this:152153.. click:run::154155 invoke(cli, prog_name='my-app', args=['validate', 'build'])156157When using chaining, there are a few restrictions:158159- Only the last command may use ``nargs=-1`` on an argument, otherwise the160 parser will not be able to find further commands.161- It is not possible to nest groups below a chain group.162- On the command line, options must be specified before arguments for each163 command in the chain.164- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the165 parser doesn't know the full list of commands that will run yet.166167.. _command-pipelines:168169Command Pipelines170------------------171172When using chaining, a common pattern is to have each command process the173result of the previous command.174175A straightforward way to do this is to use :func:`make_pass_decorator` to pass176a context object to each command, and store and read the data on that object.177178.. click:example::179180 pass_ns = click.make_pass_decorator(dict, ensure=True)181182 @click.group(chain=True)183 @click.argument("name")184 @pass_ns185 def cli(ns, name):186 ns["name"] = name187188 @cli.command189 @pass_ns190 def lower(ns):191 ns["name"] = ns["name"].lower()192193 @cli.command194 @pass_ns195 def show(ns):196 click.echo(ns["name"])197198.. click:run::199200 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])201202Another way to do this is to collect data returned by each command, then process203it at the end of the chain. Use the group's :meth:`~Group.result_callback`204decorator to register a function that is called after the chain is finished. It205is passed the list of return values as well as any parameters registered on the206group.207208A command can return anything, including a function. Here's an example of that,209where each subcommand creates a function that processes the input, then the210result callback calls each function. The command takes a file, processes each211line, then outputs it. If no subcommands are given, it outputs the contents212of the file unchanged.213214.. code-block:: python215216 @click.group(chain=True, invoke_without_command=True)217 @click.argument("fin", type=click.File("r"))218 def cli(fin):219 pass220221 @cli.result_callback()222 def process_pipeline(processors, fin):223 iterator = (x.rstrip("\r\n") for x in input)224225 for processor in processors:226 iterator = processor(iterator)227228 for item in iterator:229 click.echo(item)230231 @cli.command("upper")232 def make_uppercase():233 def processor(iterator):234 for line in iterator:235 yield line.upper()236 return processor237238 @cli.command("lower")239 def make_lowercase():240 def processor(iterator):241 for line in iterator:242 yield line.lower()243 return processor244245 @cli.command("strip")246 def make_strip():247 def processor(iterator):248 for line in iterator:249 yield line.strip()250 return processor251252That's a lot in one go, so let's go through it step by step.2532541. The first thing is to make a :func:`group` that is chainable. In255 addition to that we also instruct Click to invoke even if no256 subcommand is defined. If this would not be done, then invoking an257 empty pipeline would produce the help page instead of running the258 result callbacks.2592. The next thing we do is to register a result callback on our group.260 This callback will be invoked with an argument which is the list of261 all return values of all subcommands and then the same keyword262 parameters as our group itself. This means we can access the input263 file easily there without having to use the context object.2643. In this result callback we create an iterator of all the lines in the265 input file and then pass this iterator through all the returned266 callbacks from all subcommands and finally we print all lines to267 stdout.268269After that point we can register as many subcommands as we want and each270subcommand can return a processor function to modify the stream of lines.271272One important thing of note is that Click shuts down the context after273each callback has been run. This means that for instance file types274cannot be accessed in the `processor` functions as the files will already275be closed there. This limitation is unlikely to change because it would276make resource handling much more complicated. For such it's recommended277to not use the file type and manually open the file through278:func:`open_file`.279280For a more complex example that also improves upon handling of the pipelines,281see the `imagepipe example`_ in the Click repository. It implements a282pipeline based image editing tool that has a nice internal structure.283284.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe285286287Overriding Defaults288-------------------289290By default, the default value for a parameter is pulled from the291``default`` flag that is provided when it's defined, but that's not the292only place defaults can be loaded from. The other place is the293:attr:`Context.default_map` (a dictionary) on the context. This allows294defaults to be loaded from a configuration file to override the regular295defaults.296297This is useful if you plug in some commands from another package but298you're not satisfied with the defaults.299300The default map can be nested arbitrarily for each subcommand:301302.. code-block:: python303304 default_map = {305 "debug": True, # default for a top level option306 "runserver": {"port": 5000} # default for a subcommand307 }308309The default map can be provided when the script is invoked, or310overridden at any point by commands. For instance, a top-level command311could load the defaults from a configuration file.312313Example usage:314315.. click:example::316317 import click318319 @click.group()320 def cli():321 pass322323 @cli.command()324 @click.option('--port', default=8000)325 def runserver(port):326 click.echo(f"Serving on http://127.0.0.1:{port}/")327328 if __name__ == '__main__':329 cli(default_map={330 'runserver': {331 'port': 5000332 }333 })334335And in action:336337.. click:run::338339 invoke(cli, prog_name='cli', args=['runserver'], default_map={340 'runserver': {341 'port': 5000342 }343 })344345Context Defaults346----------------347348.. versionadded:: 2.0349350Starting with Click 2.0 you can override defaults for contexts not just351when calling your script, but also in the decorator that declares a352command. For instance given the previous example which defines a custom353``default_map`` this can also be accomplished in the decorator now.354355This example does the same as the previous example:356357.. click:example::358359 import click360361 CONTEXT_SETTINGS = dict(362 default_map={'runserver': {'port': 5000}}363 )364365 @click.group(context_settings=CONTEXT_SETTINGS)366 def cli():367 pass368369 @cli.command()370 @click.option('--port', default=8000)371 def runserver(port):372 click.echo(f"Serving on http://127.0.0.1:{port}/")373374 if __name__ == '__main__':375 cli()376377And again the example in action:378379.. click:run::380381 invoke(cli, prog_name='cli', args=['runserver'])382383384Command Return Values385---------------------386387.. versionadded:: 3.0388389One of the new introductions in Click 3.0 is the full support for return390values from command callbacks. This enables a whole range of features391that were previously hard to implement.392393In essence any command callback can now return a value. This return value394is bubbled to certain receivers. One usecase for this has already been395show in the example of :ref:`command-chaining` where it has been396demonstrated that chained groups can have callbacks that process397all return values.398399When working with command return values in Click, this is what you need to400know:401402- The return value of a command callback is generally returned from the403 :meth:`Command.invoke` method. The exception to this rule has to404 do with :class:`Group`\s:405406 * In a group the return value is generally the return value of the407 subcommand invoked. The only exception to this rule is that the408 return value is the return value of the group callback if it's409 invoked without arguments and `invoke_without_command` is enabled.410 * If a group is set up for chaining then the return value is a list411 of all subcommands' results.412 * Return values of groups can be processed through a413 :attr:`Group.result_callback`. This is invoked with the414 list of all return values in chain mode, or the single return415 value in case of non chained commands.416417- The return value is bubbled through from the :meth:`Context.invoke`418 and :meth:`Context.forward` methods. This is useful in situations419 where you internally want to call into another command.420421- Click does not have any hard requirements for the return values and422 does not use them itself. This allows return values to be used for423 custom decorators or workflows (like in the command chaining424 example).425426- When a Click script is invoked as command line application (through427 :meth:`Command.main`) the return value is ignored unless the428 `standalone_mode` is disabled in which case it's bubbled through.
modified:docs/index.rst+1 added
77 unmodified lines
78 :maxdepth: 17980 entry-points81 setuptools82 standalone-apps83 upgrade-guides84 support-multiple-versions8586Conceptual Guides
59 unmodified lines
modified:docs/options.md+92 added-5 removed
339 unmodified lines
340 invoke(info, args=['--lower'])341 invoke(info)342```343344````{note}345The `default` value is given to the decorated function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.344### How `default` and `flag_value` interact345347But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the decorated function receiving the `True` Python value, it will receive the `flag_value`.346The `default` value is given to the underlying function347as-is. So if you set `default=None`, the function receives348`None`. Same for any other type.349349Which means, in example above, this option:350But there is a special case for **non-boolean** flags: if a351flag has a non-boolean `flag_value` (like a string or a352class), then `default=True` is interpreted as *the flag353should be activated by default*. The function receives the354`flag_value`, not the Python `True`.355356Which means, in the example above, this option:357358```python359@click.option('--upper', 'transformation', flag_value='upper', default=True)360```361
2 unmodified lines
364```python365@click.option('--upper', 'transformation', flag_value='upper', default='upper')366```367361Because the two are equivalent, it is recommended to always set `default` to the actual value you want to pass and avoid using the special `True` case. This makes the code more explicit and predictable.368Because the two are equivalent, it is recommended to always369use the second form and set `default` to the actual value370you want. This makes code more explicit and predictable.371372This special case does **not** apply to boolean flags (where373`flag_value` is `True` or `False`). For boolean flags,374`default=True` is the literal Python value `True`.375376The tables below show the value received by the function for377each combination of `default`, `flag_value`, and whether378the flag was passed on the command line.379380#### Boolean flags (`is_flag=True`, boolean `flag_value`)381382These are flags where `flag_value` is `True` or `False`.383The `default` value is always passed through literally384without any special substitution.385386| `default` | `flag_value` | Not passed | `--flag` passed |387|-----------|--------------|------------|-----------------|388| *(unset)* | *(unset)* | `False` | `True` |389| `True` | *(unset)* | `True` | `True` |390| `False` | *(unset)* | `False` | `True` |391| `None` | *(unset)* | `None` | `True` |392| `True` | `True` | `True` | `True` |393| `True` | `False` | `True` | `False` |394| `False` | `True` | `False` | `True` |395| `False` | `False` | `False` | `False` |396| `None` | `True` | `None` | `True` |397| `None` | `False` | `None` | `False` |398399````{tip}400For a negative flag that defaults to off, prefer the401explicit pair form `--with-xyz/--without-xyz` over the402single-flag `flag_value=False, default=True`:403404```python405@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)406```407````408409#### Boolean flag pairs (`--flag/--no-flag`)410411These use secondary option names to provide both an on and412off switch. The `default` value is always literal.413414| `default` | Not passed | `--flag` | `--no-flag` |415|-----------|------------|----------|-------------|416| *(unset)* | `False` | `True` | `False` |417| `True` | `True` | `True` | `False` |418| `False` | `False` | `True` | `False` |419| `None` | `None` | `True` | `False` |420421#### Non-boolean feature switches (`flag_value` is a string, class, etc.)422423For these flags, `default=True` is a **special case**: it424means "activate this flag by default" and resolves to the425`flag_value`. All other `default` values are passed through426literally.427428| `default` | `flag_value` | Not passed | `--flag` passed |429|------------|--------------|-------------|-----------------|430| *(unset)* | `"upper"` | `None` | `"upper"` |431| `True` | `"upper"` | `"upper"`¹ | `"upper"` |432| `"lower"` | `"upper"` | `"lower"` | `"upper"` |433| `None` | `"upper"` | `None` | `"upper"` |434435```{hint}436¹: `default=True` is substituted with `flag_value`.437```438439#### Feature switch groups (multiple flags sharing one variable)440441When multiple `flag_value` options target the same parameter442name, `default=True` on one of them marks it as the default443choice.444445| Definition | Not passed | `--upper` | `--lower` |446|--------------------------------------------------------|------------|-----------|-----------|447| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |448| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |449| Both without `default` | `None` | `"upper"` | `"lower"` |450451## Values from Environment Variables452453To pass in a value from a specific environment variable use `envvar`.454
133 unmodified lines
added:docs/standalone-apps.md+148 added
1# Standalone Application with Briefcase23[Briefcase](https://briefcase.beeware.org/) is a tool for packaging Python4projects as standalone native applications. It can produce installers and5executables for macOS, Windows, and Linux that do not require the user to6install Python or any dependencies.78- Produces platform-native installers (``.pkg`` on macOS, ``.msi`` on9 Windows, ``.deb``/``.rpm`` on Linux).10- Bundles a Python interpreter and all dependencies.11- Supports passing command line arguments to the app.1213This page outlines the basics of packaging a Click application with14Briefcase. Be sure to read its15[documentation](https://briefcase.beeware.org/en/stable/how-to/building/cli-apps/)16and use ``briefcase --help`` to understand what features are available.1718## Installation1920Install Briefcase in the virtual environment:2122```console23pip install briefcase24```2526## Configuration2728Add a ``[tool.briefcase]`` section and a29``[tool.briefcase.app.<app-name>]`` section to ``pyproject.toml``.30Set ``console_app = true`` so Briefcase treats the project as a command31line application rather than a GUI application.3233Given a Click application with the following project structure:3435```text36hello-cli/37 src/38 hello_cli/39 __init__.py40 app.py41 LICENSE42 pyproject.toml43```4445Where ``app.py`` contains a Click command:4647```python48import click4950@click.command()51@click.argument("name", default="World")52@click.option("--count", default=1, help="Number of times to greet.")53def main(name, count):54 """Greet someone by NAME (default: World)."""55 for _ in range(count):56 click.echo(f"Hello, {name}!")57```5859Add the following Briefcase configuration to ``pyproject.toml``:6061```toml62[tool.briefcase]63project_name = "Hello CLI"64bundle = "com.example"65version = "0.0.1"66url = "https://example.com/hello-cli"67license.file = "LICENSE"68author = "Your Name"69author_email = "you@example.com"7071[tool.briefcase.app.hello-cli]72formal_name = "Hello CLI"73description = "My first application"74long_description = """More details about the app should go here.75"""76sources = [77 "src/hello_cli",78]79console_app = true80requires = [81 "click",82]83```8485The key settings are:8687- ``console_app = true`` -- tells Briefcase this is a terminal88 application, not a GUI.89- ``sources`` -- the list of source packages to include.90- ``requires`` -- the Python dependencies to bundle (Click and any other91 libraries the project needs).9293## Entry Point9495Briefcase launches the application by running the package with96``python -m <package>``, so a ``__main__.py`` file **must** exist in the97package. Without it, Briefcase will not be able to start the application.9899Create ``__main__.py`` in the package directory and call the Click100command:101102```python103from hello_cli.app import main104105if __name__ == "__main__":106 main()107```108109## Running110111Use ``briefcase dev`` to run the application directly from the source112tree. Pass command line arguments after ``--``:113114```console115$ briefcase dev -- World116Hello, World!117$ briefcase dev -- World --count 2118Hello, World!119Hello, World!120```121122## Building and Packaging123124To create a distributable executable, run the following commands:125126```console127briefcase create128briefcase build129briefcase package130```131132``briefcase create`` downloads a Python interpreter and installs133dependencies into an isolated app bundle. ``briefcase build`` compiles134the app, and ``briefcase package`` produces the final platform installer.135136On macOS, this produces a ``.pkg`` installer. On Windows, it produces a137``.msi`` installer. On Linux, it produces a system package (``.deb``,138``.rpm``, etc.) for the current distribution.139140Once installed, users can run the application directly from the terminal:141142```console143$ hello-cli World144Hello, World!145$ hello-cli World --count 2146Hello, World!147Hello, World!148```
modified:docs/testing.md+48 added
194 unmodified lines
195196Prompts will be emulated so they write the input data to197the output stream as well. If hidden input is expected then this198does not happen.199200## File Descriptors and Low-Level I/O201202{class}`CliRunner` captures output by replacing203`sys.stdout` and `sys.stderr` with in-memory204{class}`~io.BytesIO`-backed wrappers. This is205Python-level redirection: calls to {func}`~click.echo`,206{func}`print`, or `sys.stdout.write()` are captured, but207the wrappers have no OS-level file descriptor.208209Code that calls `fileno()` on `sys.stdout` or210`sys.stderr`, like {mod}`faulthandler`,211{mod}`subprocess`, or C extensions, would normally crash212with {exc}`io.UnsupportedOperation` inside213{class}`CliRunner`.214215To avoid this, {class}`CliRunner` preserves the original216stream's file descriptor and exposes it via `fileno()` on217the replacement wrapper.218219This means:220- **Python-level writes** (`print()`, `click.echo()`,221 ...) are captured as usual.222- **fd-level writes** (C code writing directly to the223 file descriptor) go to the original terminal and are224 **not** captured.225226This is the same trade-off that227[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228makes with its two capture modes:229230- `capsys`, which captures Python-level output, where231 `fileno()` raises `UnsupportedOperation` and fd-level232 writes are not captured.233- `capfd`, which captures fd-level output via234 `os.dup2()`, where `fileno()` works and fd-level235 writes *are* captured.236237Rather than implementing a full `capfd`-style mechanism,238{class}`CliRunner` takes the simpler path: expose the239original `fd` so that standard library helpers keep240working, while accepting that their output is not241captured.242243```{versionchanged} 8.3.3244`fileno()` on the redirected streams now returns the245original stream's file descriptor instead of raising.246```
modified:src/click/core.py+24 added-5 removed
2889 unmodified lines
28902891 def get_default(2892 self, ctx: Context, call: bool = True2893 ) -> t.Any | t.Callable[[], t.Any] | None:2894 """For non-boolean flag options, ``default=True`` is treated as a2895 sentinel meaning "activate this flag by default" and is resolved to2896 :attr:`flag_value`. This resolution is performed lazily here (rather2897 than eagerly in :meth:`__init__`) to prevent callable ``flag_value``2898 values (like classes) from being instantiated prematurely.28992900 For example, with ``--upper/--lower`` feature switches where2901 ``flag_value="upper"`` and ``default=True``, the default resolves2902 to ``"upper"``.29032904 .. caution::2905 This substitution only applies to **non-boolean** flags2906 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is2907 not a sentinel but a legitimate Python value, so ``default=True`` is2908 returned as-is. Without this distinction, ``flag_value=False,2909 default=True`` would silently always return ``False``, regardless of2910 whether the flag was passed or not.29112912 .. versionchanged:: 8.3.32913 ``default=True`` is no longer substituted with ``flag_value`` for2914 boolean flags, fixing negative boolean flags like ``flag_value=False,2915 default=True``.2916 """2917 value = super().get_default(ctx, call=False)29182896 # Lazily resolve default=True to flag_value. Doing this here2897 # (instead of eagerly in __init__) prevents callable flag_values2898 # (like classes) from being instantiated by the callable check below.2899 # https://github.com/pallets/click/issues/31212900 if value is True and self.is_flag:2919 if value is True and self.is_flag and not self.is_bool_flag:2920 value = self.flag_value2921 elif call and callable(value):2922 value = value()2923
533 unmodified lines
modified:src/click/testing.py+59 added-6 removed
99 unmodified lines
100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101102103class _NamedTextIOWrapper(io.TextIOWrapper):104 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105 that does not close its underlying buffer.106107 An optional ``original_fd`` preserves the file descriptor of the108 stream being replaced, so that C-level consumers that call109 :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110 Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111 for details.112113 .. versionchanged:: 8.3.3114 Added ``original_fd`` parameter and :meth:`fileno` override.115 """116117 def __init__(105 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any118 self,119 buffer: t.BinaryIO,120 name: str,121 mode: str,122 *,123 original_fd: int = -1,124 **kwargs: t.Any,125 ) -> None:126 super().__init__(buffer, **kwargs)127 self._name = name128 self._mode = mode129 self._original_fd = original_fd130131 def close(self) -> None:112 """113 The buffer this object contains belongs to some other object, so114 prevent the default __del__ implementation from closing that buffer.132 """The buffer this object contains belongs to some other object,133 so prevent the default ``__del__`` implementation from closing134 that buffer.135136 .. versionadded:: 8.3.2137 """118 ...138139 def fileno(self) -> int:140 """Return the file descriptor of the original stream, if one was141 provided at construction time.142143 This allows C-level consumers (``faulthandler``, ``subprocess``,144 signal handlers, ...) to obtain a valid fd without crashing, even145 though the Python-level writes are redirected to an in-memory146 buffer.147148 .. versionadded:: 8.3.3149 """150 if self._original_fd >= 0:151 return self._original_fd152 return super().fileno()153154 @property155 def name(self) -> str:156 return self._name157
196 unmodified lines
354 env = self.make_env(env)355356 stream_mixer = StreamMixer()357358 # Preserve the original file descriptors so that C-level359 # consumers (faulthandler, subprocess, etc.) can still obtain a360 # valid fd from the redirected streams. The original streams361 # may themselves lack a fileno() (e.g. when CliRunner is used362 # inside pytest's capsys), so we fall back to -1.363 def _safe_fileno(stream: t.IO[t.Any]) -> int:364 try:365 return stream.fileno()366 except (AttributeError, io.UnsupportedOperation):367 return -1368369 old_stdout_fd = _safe_fileno(old_stdout)370 old_stderr_fd = _safe_fileno(old_stderr)371372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )
7 unmodified lines
383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385386 sys.stdout = _NamedTextIOWrapper(339 stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"387 stream_mixer.stdout,388 encoding=self.charset,389 name="<stdout>",390 mode="w",391 original_fd=old_stdout_fd,392 )393394 sys.stderr = _NamedTextIOWrapper(395 stream_mixer.stderr,396 encoding=self.charset,397 name="<stderr>",398 mode="w",399 errors="backslashreplace",400 original_fd=old_stderr_fd,401 )402403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:
268 unmodified lines
modified:src/click/utils.py+4 added-1 removed
55 unmodified lines
56 return str(value)575859def make_default_short_help(help: str, max_length: int = 45) -> str:60 """Returns a condensed version of help string."""60 """Returns a condensed version of help string.6162 :meta private:63 """64 # Consider only the first paragraph.65 paragraph_end = help.find("\n\n")6667 if paragraph_end != -1:
563 unmodified lines
modified:tests/test_options.py+37 added-2 removed
1468 unmodified lines
1469 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1470 ({"type": str, "flag_value": None}, [], None),1471 ({"type": str, "flag_value": None}, ["--foo"], None),1472 # Not passing --foo returns the default value as-is, in its Python type, then1473 # converted by the option type.1473 # converted by the option type. For boolean flags, default=True is a literal1474 # value, not a sentinel meaning "activate flag". So it is NOT substituted with1475 # flag_value. See: https://github.com/pallets/click/issues/31111476 # https://github.com/pallets/click/pull/32391477 ({"type": bool, "default": True, "flag_value": True}, [], True),1475 ({"type": bool, "default": True, "flag_value": False}, [], False),1478 ({"type": bool, "default": True, "flag_value": False}, [], True),1479 ({"type": bool, "default": False, "flag_value": True}, [], False),1480 ({"type": bool, "default": False, "flag_value": False}, [], False),1481 ({"type": bool, "default": None, "flag_value": True}, [], None),1482 ({"type": bool, "default": None, "flag_value": False}, [], None),
1017 unmodified lines
2500 assert result.exit_code == 0250125022503@pytest.mark.parametrize(2504 ("default", "args", "expected"),2505 [2506 # default=None: 3-state pattern (e.g. Flask --reload/--no-reload).2507 # https://github.com/pallets/click/issues/30242508 (None, [], None),2509 (None, ["--flag"], True),2510 (None, ["--no-flag"], False),2511 # default=True: literal value, not substituted with flag_value.2512 # https://github.com/pallets/click/issues/31112513 (True, [], True),2514 (True, ["--flag"], True),2515 (True, ["--no-flag"], False),2516 ],2517)2518def test_bool_flag_pair_default(runner, default, args, expected):2519 """Boolean flag pairs pass ``default`` through literally.25202521 Ensures ``default=True`` is not replaced by ``flag_value`` for boolean2522 flags, and that ``default=None`` enables 3-state logic.2523 """25242525 @click.command()2526 @click.option("--flag/--no-flag", default=default)2527 def cli(flag):2528 click.echo(repr(flag), nl=False)25292530 result = runner.invoke(cli, args)2531 assert result.exit_code == 02532 assert result.output == repr(expected)253325342535@pytest.mark.parametrize(2536 ("flag_type", "args", "expect_output"),2537 [2538 (str, [], "Default\n"),2539 (str, ["--theflag"], "FlagValue\n"),
36 unmodified lines
modified:tests/test_termui.py+7 added-3 removed
876 unmodified lines
877 # default=True878 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),879 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),880 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),881 # For boolean flags, default=True is a literal value, not a sentinel meaning882 # "activate flag", so the prompt shows [Y/n] with default=True. See:883 # https://github.com/pallets/click/issues/3111884 # https://github.com/pallets/click/pull/3239881 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),882 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),883 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),885 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),886 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),887 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),888 # default=False889 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),890 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),891 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),
99 unmodified lines
modified:tests/test_testing.py+26 added
1import faulthandler2import os3import pdb4import sys5from io import BytesIO
513 unmodified lines
519 runner = CliRunner()520 runner.invoke(cli)521522 assert pdb.Pdb.__init__ is original523524525def test_faulthandler_enable(runner):526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527 ``io.UnsupportedOperation: fileno``.528529 ``faulthandler.enable()`` needs a real OS file descriptor to register530 its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531 ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.532533 Reproduce:https://github.com/pallets/click/issues/2865534 """535536 @click.command()537 @click.option("--flag", type=bool, default=True)538 def cli(flag):539 click.echo("Executing main function...")540 if flag:541 click.echo("Registering faulthandler")542 faulthandler.enable()543 click.echo("Finished executing main function.")544545 result = runner.invoke(cli, ["--flag", True])546 assert result.exit_code == 0, result.output547 assert "Finished executing main function." in result.output
modified:CHANGES.rst+10 added
22 unmodified lines
23 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`24- Show custom ``show_default`` string in prompts, matching the existing25 help text behavior. :issue:`2836` :pr:`2837` :pr:`3165` :pr:`3262` :pr:`3280`26 :pr:`3328``27- Fix ``default=True`` with boolean ``flag_value`` always returning the28 ``flag_value`` instead of ``True``. The ``default=True`` to ``flag_value``29 substitution now only applies to non-boolean flags, where ``True`` acts as a30 sentinel meaning "activate this flag by default". For boolean flags,31 ``default=True`` is returned as a literal value. :issue:`3111` :pr:`3239`32- Mark ``make_default_short_help`` as private API. :issue:`3189` :pr:`3250`33- ``CliRunner``'s redirected streams now expose the original file descriptor34 via ``fileno()``, so that ``faulthandler``, ``subprocess``, and other35 C-level consumers no longer crash with ``io.UnsupportedOperation``.36 :issue:`2865`3738Version 8.3.239-------------40
1323 unmodified lines