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
Provenance
- Commit
8c452e0- Tree
e736f5f- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
39413d9- Parent 2
8c95c73
15 files changed+1265 added−792 removed
added:docs/commands-and-groups.md+372 added
1+# Basic Commands, Groups, Context2+3+```{currentmodule} click4+```5+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+---10+depth: 211+local: true12+---13+```14+15+## Commands16+17+### Basic Command Example18+19+A simple command decorator takes no arguments.20+21+```{eval-rst}22+.. click:example::23+24+ @click.command()25+ @click.option('--count', default=1)26+ def hello(count):27+ for x in range(count):28+ click.echo("Hello!")29+30+.. click:run::31+ invoke(hello, args=['--count', '2',])32+```33+34+### Renaming Commands35+36+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.37+38+```{eval-rst}39+.. click:example::40+41+ @click.command('say-hello')42+ @click.option('--count', default=1)43+ def hello(count):44+ for x in range(count):45+ click.echo("Hello!")46+47+.. click:run::48+ invoke(hello, args=['--count', '2',])49+```50+51+### Deprecating Commands52+53+To mark a command as deprecated pass in `deprecated=True`54+55+```{eval-rst}56+.. click:example::57+58+ @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!")63+64+.. click:run::65+ invoke(hello, args=['--count', '2',])66+```67+68+## Groups69+70+### Basic Group Example71+72+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.73+74+```{eval-rst}75+.. click:example::76+77+ @click.group()78+ def greeting():79+ click.echo('Starting greeting ...')80+81+ @greeting.command('say-hello')82+ @click.option('--count', default=1)83+ def hello(count):84+ for x in range(count):85+ click.echo("Hello!")86+87+At the top level:88+89+.. click:run::90+91+ invoke(greeting)92+93+At the command level:94+95+.. click:run::96+97+ invoke(greeting, args=['say-hello'])98+ invoke(greeting, args=['say-hello', '--help'])99+```100+101+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).102+103+### Renaming Groups104+105+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.106+107+```{eval-rst}108+.. click:example::109+110+ @click.group('greet-someone')111+ def greeting():112+ click.echo('Starting greeting ...')113+114+ @greeting.command('say-hello')115+ @click.option('--count', default=1)116+ def hello(count):117+ for x in range(count):118+ click.echo("Hello!")119+120+.. click:run::121+122+ invoke(greeting, args=['say-hello'])123+```124+125+### Group Invocation Without Command126+127+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.128+129+```{eval-rst}130+.. click:example::131+132+ @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}")139+140+ @cli.command()141+ def sync():142+ click.echo('The subcommand')143+144+.. click:run::145+146+ invoke(cli, prog_name='tool', args=[])147+ invoke(cli, prog_name='tool', args=['sync'])148+```149+150+### Group Separation151+152+Command {ref}`parameters` attached to a command belong only to that command.153+154+```{eval-rst}155+.. click:example::156+157+ @click.group()158+ def greeting():159+ pass160+161+ @greeting.command()162+ @click.option('--count', default=1)163+ def hello(count):164+ for x in range(count):165+ click.echo("Hello!")166+167+ @greeting.command()168+ @click.option('--count', default=1)169+ def goodbye(count):170+ for x in range(count):171+ click.echo("Goodbye!")172+173+.. click:run::174+175+ invoke(greeting, args=['hello', '--count', '2'])176+ invoke(greeting, args=['goodbye', '--count', '2'])177+ invoke(greeting)178+```179+180+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.181+182+This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.183+184+- `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.187+188+### Arbitrary Nesting189+190+{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.191+192+```{eval-rst}193+.. click:example::194+195+ @click.group()196+ def cli():197+ pass198+199+ # Not @click so that the group is registered now.200+ @cli.group()201+ def session():202+ click.echo('Starting session')203+204+ @session.command()205+ def initdb():206+ click.echo('Initialized the database')207+208+ @session.command()209+ def dropdb():210+ click.echo('Dropped the database')211+212+.. click:run::213+214+ invoke(cli, args=['session', 'initdb'])215+```216+217+### Lazily Attaching Commands218+219+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.220+221+```{eval-rst}222+.. click:example::223+224+ @click.group()225+ def cli():226+ pass227+228+ @cli.command()229+ def initdb():230+ click.echo('Initialized the database')231+232+ @click.command()233+ def dropdb():234+ click.echo('Dropped the database')235+236+ cli.add_command(dropdb)237+238+.. click:run::239+240+ invoke(cli, args=['initdb'])241+ invoke(cli, args=['dropdb'])242+```243+244+## Context Object245+The {class}`Context` object is how commands and groups communicate.246+247+### Auto Envvar Prefix248+249+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 subcommand250+called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.251+252+Example usage:253+254+```{eval-rst}255+.. click:example::256+257+ @click.command()258+ @click.option('--username')259+ def greet(username):260+ click.echo(f'Hello {username}!')261+262+ if __name__ == '__main__':263+ greet(auto_envvar_prefix='GREETER')264+265+And from the command line:266+267+.. click:run::268+269+ invoke(greet, env={'GREETER_USERNAME': 'john'},270+ auto_envvar_prefix='GREETER')271+```272+273+When using `auto_envvar_prefix` with command groups, the command name274+needs to be included in the environment variable, between the prefix and275+the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a276+subcommand called `run-server` taking an option called `host` and277+the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.278+279+```{eval-rst}280+.. click:example::281+282+ @click.group()283+ @click.option('--debug/--no-debug')284+ def cli(debug):285+ click.echo(f"Debug mode is {'on' if debug else 'off'}")286+287+ @cli.command()288+ @click.option('--username')289+ def greet(username):290+ click.echo(f"Hello {username}!")291+292+ if __name__ == '__main__':293+ cli(auto_envvar_prefix='GREETER')294+295+.. click:run::296+297+ invoke(cli, args=['greet',],298+ env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},299+ auto_envvar_prefix='GREETER')300+```301+302+### Global Context Access303+304+```{versionadded} 5.0305+```306+307+Starting with Click 5.0 it is possible to access the current context from308+anywhere within the same thread through the use of the309+{func}`get_current_context` function which returns it. This is primarily310+useful for accessing the context bound object as well as some flags that311+are stored on it to customize the runtime behavior. For instance the312+{func}`echo` function does this to infer the default value of the `color`313+flag.314+315+Example usage:316+317+```python318+ def get_current_command_name():319+ return click.get_current_context().info_name320+```321+322+It should be noted that this only works within the current thread. If you323+spawn additional threads then those threads will not have the ability to324+refer to the current context. If you want to give another thread the325+ability to refer to this context you need to use the context within the326+thread as a context manager:327+328+```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+```337+338+Now the thread function can access the context like the main thread would339+do. However if you do use this for threading you need to be very careful340+as the vast majority of the context is not thread safe! You are only341+allowed to read from the context, but not to perform any modifications on342+it.343+344+345+### Detecting the Source of a Parameter346+347+In some situations it's helpful to understand whether or not an option348+or parameter came from the command line, the environment, the default349+value, or {attr}`Context.default_map`. The350+{meth}`Context.get_parameter_source` method can be used to find this351+out. It will return a member of the {class}`~click.core.ParameterSource`352+enum.353+354+```{eval-rst}355+.. click:example::356+357+ @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}")363+364+.. click:run::365+366+ 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
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()added:docs/commands.md+437 added
1+# Advanced Groups and Context2+3+```{currentmodule} click4+```5+6+In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7+8+```{contents}9+---10+depth: 111+local: true12+---13+```14+15+## Callback Invocation16+17+For a regular command, the callback is executed whenever the command runs.18+If the script is the only command, it will always fire (unless a parameter19+callback prevents it. This for instance happens if someone passes20+`--help` to the script).21+22+For groups, the situation looks different. In this case, the callback fires23+whenever a subcommand fires. What this means in practice is that an outer24+command runs when an inner command runs:25+26+```{eval-rst}27+.. click:example::28+29+ @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'}")33+34+ @cli.command() # @cli, not @click!35+ def sync():36+ click.echo('Syncing')37+38+Here is what this looks like:39+40+.. click:run::41+42+ invoke(cli, prog_name='tool.py')43+ println()44+ invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])45+```46+47+## Nested Handling and Contexts48+49+As you can see from the earlier example, the basic command group accepts a50+debug argument which is passed to its callback, but not to the sync51+command itself. The sync command only accepts its own arguments.52+53+This allows tools to act completely independent of each other, but how54+does one command talk to a nested one? The answer to this is the55+{class}`Context`.56+57+Each time a command is invoked, a new context is created and linked with the58+parent context. Normally, you can't see these contexts, but they are59+there. Contexts are passed to parameter callbacks together with the60+value automatically. Commands can also ask for the context to be passed61+by marking themselves with the {func}`pass_context` decorator. In that62+case, the context is passed as first argument.63+64+The context can also carry a program specified object that can be65+used for the program's purposes. What this means is that you can build a66+script like this:67+68+```{eval-rst}69+.. click:example::70+71+ @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)78+79+ ctx.obj['DEBUG'] = debug80+81+ @cli.command()82+ @click.pass_context83+ def sync(ctx):84+ click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")85+86+ if __name__ == '__main__':87+ cli(obj={})88+```89+90+If the object is provided, each context will pass the object onwards to91+its children, but at any level a context's object can be overridden. To92+reach to a parent, `context.parent` can be used.93+94+In addition to that, instead of passing an object down, nothing stops the95+application from modifying global state. For instance, you could just flip96+a global `DEBUG` variable and be done with it.97+98+## Decorating Commands99+100+As you have seen in the earlier example, a decorator can change how a101+command is invoked. What actually happens behind the scenes is that102+callbacks are always invoked through the {meth}`Context.invoke` method103+which automatically invokes a command correctly (by either passing the104+context or not).105+106+This is very useful when you want to write custom decorators. For107+instance, a common pattern would be to configure an object representing108+state and then storing it on the context and then to use a custom109+decorator to find the most recent object of this sort and pass it as first110+argument.111+112+For instance, the {func}`pass_obj` decorator can be implemented like this:113+114+```{eval-rst}115+.. click:example::116+117+ from functools import update_wrapper118+119+ 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+```125+126+The {meth}`Context.invoke` command will automatically invoke the function127+in the correct way, so the function will either be called with`f(ctx,128+obj)` or `f(obj)` depending on whether or not it itself is decorated with129+{func}`pass_context`.130+131+This is a very powerful concept that can be used to build very complex132+nested applications; see {ref}`complex-guide` for more information.133+134+(command-chaining)=135+136+## Command Chaining137+138+It 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.141+142+```{eval-rst}143+.. click:example::144+145+ @click.group(chain=True)146+ def cli():147+ pass148+149+ @cli.command('validate')150+ def validate():151+ click.echo('validate')152+153+ @cli.command('build')154+ def build():155+ click.echo('build')156+157+You can invoke it like this:158+159+.. click:run::160+161+ invoke(cli, prog_name='my-app', args=['validate', 'build'])162+```163+164+When using chaining, there are a few restrictions:165+166+- 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.173+174+(command-pipelines)=175+176+## Command Pipelines177+178+When using chaining, a common pattern is to have each command process the179+result of the previous command.180+181+A straightforward way to do this is to use {func}`make_pass_decorator` to pass182+a context object to each command, and store and read the data on that object.183+184+```{eval-rst}185+.. click:example::186+187+ pass_ns = click.make_pass_decorator(dict, ensure=True)188+189+ @click.group(chain=True)190+ @click.argument("name")191+ @pass_ns192+ def cli(ns, name):193+ ns["name"] = name194+195+ @cli.command196+ @pass_ns197+ def lower(ns):198+ ns["name"] = ns["name"].lower()199+200+ @cli.command201+ @pass_ns202+ def show(ns):203+ click.echo(ns["name"])204+205+.. click:run::206+207+ invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])208+```209+210+Another way to do this is to collect data returned by each command, then process211+it at the end of the chain. Use the group's {meth}`~Group.result_callback`212+decorator to register a function that is called after the chain is finished. It213+is passed the list of return values as well as any parameters registered on the214+group.215+216+A command can return anything, including a function. Here's an example of that,217+where each subcommand creates a function that processes the input, then the218+result callback calls each function. The command takes a file, processes each219+line, then outputs it. If no subcommands are given, it outputs the contents220+of the file unchanged.221+222+```python223+@click.group(chain=True, invoke_without_command=True)224+@click.argument("fin", type=click.File("r"))225+def cli(fin):226+ pass227+228+@cli.result_callback()229+def process_pipeline(processors, fin):230+ iterator = (x.rstrip("\r\n") for x in input)231+232+ for processor in processors:233+ iterator = processor(iterator)234+235+ for item in iterator:236+ click.echo(item)237+238+@cli.command("upper")239+def make_uppercase():240+ def processor(iterator):241+ for line in iterator:242+ yield line.upper()243+ return processor244+245+@cli.command("lower")246+def make_lowercase():247+ def processor(iterator):248+ for line in iterator:249+ yield line.lower()250+ return processor251+252+@cli.command("strip")253+def make_strip():254+ def processor(iterator):255+ for line in iterator:256+ yield line.strip()257+ return processor258+```259+260+That's a lot in one go, so let's go through it step by step.261+262+1. 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.267+2. 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.272+3. 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.276+277+After that point we can register as many subcommands as we want and each278+subcommand can return a processor function to modify the stream of lines.279+280+One important thing of note is that Click shuts down the context after281+each callback has been run. This means that for instance file types282+cannot be accessed in the `processor` functions as the files will already283+be closed there. This limitation is unlikely to change because it would284+make resource handling much more complicated. For such it's recommended285+to not use the file type and manually open the file through286+{func}`open_file`.287+288+For a more complex example that also improves upon handling of the pipelines,289+see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe)290+in the Click repository. It implements a pipeline based image editing tool291+that has a nice internal structure.292+293+## Overriding Defaults294+295+By default, the default value for a parameter is pulled from the296+`default` flag that is provided when it's defined, but that's not the297+only place defaults can be loaded from. The other place is the298+{attr}`Context.default_map` (a dictionary) on the context. This allows299+defaults to be loaded from a configuration file to override the regular300+defaults.301+302+This is useful if you plug in some commands from another package but303+you're not satisfied with the defaults.304+305+The default map can be nested arbitrarily for each subcommand:306+307+```python308+309+ default_map = {310+ "debug": True, # default for a top level option311+ "runserver": {"port": 5000} # default for a subcommand312+ }313+```314+315+The default map can be provided when the script is invoked, or316+overridden at any point by commands. For instance, a top-level command317+could load the defaults from a configuration file.318+319+Example usage:320+321+```{eval-rst}322+.. click:example::323+324+ import click325+326+ @click.group()327+ def cli():328+ pass329+330+ @cli.command()331+ @click.option('--port', default=8000)332+ def runserver(port):333+ click.echo(f"Serving on http://127.0.0.1:{port}/")334+335+ if __name__ == '__main__':336+ cli(default_map={337+ 'runserver': {338+ 'port': 5000339+ }340+ })341+342+And in action:343+344+.. click:run::345+346+ invoke(cli, prog_name='cli', args=['runserver'], default_map={347+ 'runserver': {348+ 'port': 5000349+ }350+ })351+```352+353+## Context Defaults354+355+```{versionadded} 2.0356+```357+358+Starting with Click 2.0 you can override defaults for contexts not just359+when calling your script, but also in the decorator that declares a360+command. For instance given the previous example which defines a custom361+`default_map` this can also be accomplished in the decorator now.362+363+This example does the same as the previous example:364+365+```{eval-rst}366+.. click:example::367+368+ import click369+370+ CONTEXT_SETTINGS = dict(371+ default_map={'runserver': {'port': 5000}}372+ )373+374+ @click.group(context_settings=CONTEXT_SETTINGS)375+ def cli():376+ pass377+378+ @cli.command()379+ @click.option('--port', default=8000)380+ def runserver(port):381+ click.echo(f"Serving on http://127.0.0.1:{port}/")382+383+ if __name__ == '__main__':384+ cli()385+386+And again the example in action:387+388+.. click:run::389+390+ invoke(cli, prog_name='cli', args=['runserver'])391+```392+393+## Command Return Values394+395+```{versionadded} 3.0396+```397+398+One of the new introductions in Click 3.0 is the full support for return399+values from command callbacks. This enables a whole range of features400+that were previously hard to implement.401+402+In essence any command callback can now return a value. This return value403+is bubbled to certain receivers. One usecase for this has already been404+show in the example of {ref}`command-chaining` where it has been405+demonstrated that chained groups can have callbacks that process406+all return values.407+408+When working with command return values in Click, this is what you need to409+know:410+411+- 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:414+415+ - 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.425+426+- 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.429+430+- 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).434+435+- 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
1-Advanced Groups and Context2-=============================3-4-.. currentmodule:: click5-6-In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7-8-.. contents::9- :depth: 110- :local:11-12-Callback Invocation13--------------------14-15-For a regular command, the callback is executed whenever the command runs.16-If the script is the only command, it will always fire (unless a parameter17-callback prevents it. This for instance happens if someone passes18-``--help`` to the script).19-20-For groups, the situation looks different. In this case, the callback fires21-whenever a subcommand fires. What this means in practice is that an outer22-command runs when an inner command runs:23-24-.. click:example::25-26- @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'}")30-31- @cli.command() # @cli, not @click!32- def sync():33- click.echo('Syncing')34-35-Here is what this looks like:36-37-.. click:run::38-39- invoke(cli, prog_name='tool.py')40- println()41- invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])42-43-Nested Handling and Contexts44-----------------------------45-46-As you can see from the earlier example, the basic command group accepts a47-debug argument which is passed to its callback, but not to the sync48-command itself. The sync command only accepts its own arguments.49-50-This allows tools to act completely independent of each other, but how51-does one command talk to a nested one? The answer to this is the52-:class:`Context`.53-54-Each time a command is invoked, a new context is created and linked with the55-parent context. Normally, you can't see these contexts, but they are56-there. Contexts are passed to parameter callbacks together with the57-value automatically. Commands can also ask for the context to be passed58-by marking themselves with the :func:`pass_context` decorator. In that59-case, the context is passed as first argument.60-61-The context can also carry a program specified object that can be62-used for the program's purposes. What this means is that you can build a63-script like this:64-65-.. click:example::66-67- @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)74-75- ctx.obj['DEBUG'] = debug76-77- @cli.command()78- @click.pass_context79- def sync(ctx):80- click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")81-82- if __name__ == '__main__':83- cli(obj={})84-85-If the object is provided, each context will pass the object onwards to86-its children, but at any level a context's object can be overridden. To87-reach to a parent, ``context.parent`` can be used.88-89-In addition to that, instead of passing an object down, nothing stops the90-application from modifying global state. For instance, you could just flip91-a global ``DEBUG`` variable and be done with it.92-93-Decorating Commands94--------------------95-96-As you have seen in the earlier example, a decorator can change how a97-command is invoked. What actually happens behind the scenes is that98-callbacks are always invoked through the :meth:`Context.invoke` method99-which automatically invokes a command correctly (by either passing the100-context or not).101-102-This is very useful when you want to write custom decorators. For103-instance, a common pattern would be to configure an object representing104-state and then storing it on the context and then to use a custom105-decorator to find the most recent object of this sort and pass it as first106-argument.107-108-For instance, the :func:`pass_obj` decorator can be implemented like this:109-110-.. click:example::111-112- from functools import update_wrapper113-114- 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)119-120-The :meth:`Context.invoke` command will automatically invoke the function121-in the correct way, so the function will either be called with ``f(ctx,122-obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with123-:func:`pass_context`.124-125-This is a very powerful concept that can be used to build very complex126-nested applications; see :ref:`complex-guide` for more information.127-128-.. _command-chaining:129-130-Command Chaining131-----------------132-133-It 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.136-137-.. click:example::138-139- @click.group(chain=True)140- def cli():141- pass142-143- @cli.command('validate')144- def validate():145- click.echo('validate')146-147- @cli.command('build')148- def build():149- click.echo('build')150-151-You can invoke it like this:152-153-.. click:run::154-155- invoke(cli, prog_name='my-app', args=['validate', 'build'])156-157-When using chaining, there are a few restrictions:158-159-- 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.166-167-.. _command-pipelines:168-169-Command Pipelines170-------------------171-172-When using chaining, a common pattern is to have each command process the173-result of the previous command.174-175-A straightforward way to do this is to use :func:`make_pass_decorator` to pass176-a context object to each command, and store and read the data on that object.177-178-.. click:example::179-180- pass_ns = click.make_pass_decorator(dict, ensure=True)181-182- @click.group(chain=True)183- @click.argument("name")184- @pass_ns185- def cli(ns, name):186- ns["name"] = name187-188- @cli.command189- @pass_ns190- def lower(ns):191- ns["name"] = ns["name"].lower()192-193- @cli.command194- @pass_ns195- def show(ns):196- click.echo(ns["name"])197-198-.. click:run::199-200- invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])201-202-Another way to do this is to collect data returned by each command, then process203-it at the end of the chain. Use the group's :meth:`~Group.result_callback`204-decorator to register a function that is called after the chain is finished. It205-is passed the list of return values as well as any parameters registered on the206-group.207-208-A command can return anything, including a function. Here's an example of that,209-where each subcommand creates a function that processes the input, then the210-result callback calls each function. The command takes a file, processes each211-line, then outputs it. If no subcommands are given, it outputs the contents212-of the file unchanged.213-214-.. code-block:: python215-216- @click.group(chain=True, invoke_without_command=True)217- @click.argument("fin", type=click.File("r"))218- def cli(fin):219- pass220-221- @cli.result_callback()222- def process_pipeline(processors, fin):223- iterator = (x.rstrip("\r\n") for x in input)224-225- for processor in processors:226- iterator = processor(iterator)227-228- for item in iterator:229- click.echo(item)230-231- @cli.command("upper")232- def make_uppercase():233- def processor(iterator):234- for line in iterator:235- yield line.upper()236- return processor237-238- @cli.command("lower")239- def make_lowercase():240- def processor(iterator):241- for line in iterator:242- yield line.lower()243- return processor244-245- @cli.command("strip")246- def make_strip():247- def processor(iterator):248- for line in iterator:249- yield line.strip()250- return processor251-252-That's a lot in one go, so let's go through it step by step.253-254-1. 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.259-2. 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.264-3. 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.268-269-After that point we can register as many subcommands as we want and each270-subcommand can return a processor function to modify the stream of lines.271-272-One important thing of note is that Click shuts down the context after273-each callback has been run. This means that for instance file types274-cannot be accessed in the `processor` functions as the files will already275-be closed there. This limitation is unlikely to change because it would276-make resource handling much more complicated. For such it's recommended277-to not use the file type and manually open the file through278-:func:`open_file`.279-280-For a more complex example that also improves upon handling of the pipelines,281-see the `imagepipe example`_ in the Click repository. It implements a282-pipeline based image editing tool that has a nice internal structure.283-284-.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe285-286-287-Overriding Defaults288--------------------289-290-By default, the default value for a parameter is pulled from the291-``default`` flag that is provided when it's defined, but that's not the292-only place defaults can be loaded from. The other place is the293-:attr:`Context.default_map` (a dictionary) on the context. This allows294-defaults to be loaded from a configuration file to override the regular295-defaults.296-297-This is useful if you plug in some commands from another package but298-you're not satisfied with the defaults.299-300-The default map can be nested arbitrarily for each subcommand:301-302-.. code-block:: python303-304- default_map = {305- "debug": True, # default for a top level option306- "runserver": {"port": 5000} # default for a subcommand307- }308-309-The default map can be provided when the script is invoked, or310-overridden at any point by commands. For instance, a top-level command311-could load the defaults from a configuration file.312-313-Example usage:314-315-.. click:example::316-317- import click318-319- @click.group()320- def cli():321- pass322-323- @cli.command()324- @click.option('--port', default=8000)325- def runserver(port):326- click.echo(f"Serving on http://127.0.0.1:{port}/")327-328- if __name__ == '__main__':329- cli(default_map={330- 'runserver': {331- 'port': 5000332- }333- })334-335-And in action:336-337-.. click:run::338-339- invoke(cli, prog_name='cli', args=['runserver'], default_map={340- 'runserver': {341- 'port': 5000342- }343- })344-345-Context Defaults346-----------------347-348-.. versionadded:: 2.0349-350-Starting with Click 2.0 you can override defaults for contexts not just351-when calling your script, but also in the decorator that declares a352-command. For instance given the previous example which defines a custom353-``default_map`` this can also be accomplished in the decorator now.354-355-This example does the same as the previous example:356-357-.. click:example::358-359- import click360-361- CONTEXT_SETTINGS = dict(362- default_map={'runserver': {'port': 5000}}363- )364-365- @click.group(context_settings=CONTEXT_SETTINGS)366- def cli():367- pass368-369- @cli.command()370- @click.option('--port', default=8000)371- def runserver(port):372- click.echo(f"Serving on http://127.0.0.1:{port}/")373-374- if __name__ == '__main__':375- cli()376-377-And again the example in action:378-379-.. click:run::380-381- invoke(cli, prog_name='cli', args=['runserver'])382-383-384-Command Return Values385----------------------386-387-.. versionadded:: 3.0388-389-One of the new introductions in Click 3.0 is the full support for return390-values from command callbacks. This enables a whole range of features391-that were previously hard to implement.392-393-In essence any command callback can now return a value. This return value394-is bubbled to certain receivers. One usecase for this has already been395-show in the example of :ref:`command-chaining` where it has been396-demonstrated that chained groups can have callbacks that process397-all return values.398-399-When working with command return values in Click, this is what you need to400-know:401-402-- 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:405-406- * 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.416-417-- 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.420-421-- 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).425-426-- 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 lines78 :maxdepth: 179 80 entry-points81 setuptools82+ standalone-apps83 upgrade-guides84 support-multiple-versions85 86 Conceptual Guides59 unmodified linesmodified:docs/options.md+92 added-5 removed
339 unmodified lines340 invoke(info, args=['--lower'])341 invoke(info)342 ```343 344-````{note}345-The `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` interact345 347-But 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`.346+The `default` value is given to the underlying function347+as-is. So if you set `default=None`, the function receives348+`None`. Same for any other type.349 349-Which means, in example above, this option:350+But there is a special case for **non-boolean** flags: if a351+flag has a non-boolean `flag_value` (like a string or a352+class), then `default=True` is interpreted as *the flag353+should be activated by default*. The function receives the354+`flag_value`, not the Python `True`.355 356+Which means, in the example above, this option:357+358 ```python359 @click.option('--upper', 'transformation', flag_value='upper', default=True)360 ```361 2 unmodified lines364 ```python365 @click.option('--upper', 'transformation', flag_value='upper', default='upper')366 ```367 361-Because 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.368+Because the two are equivalent, it is recommended to always369+use the second form and set `default` to the actual value370+you want. This makes code more explicit and predictable.371+372+This 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`.375+376+The tables below show the value received by the function for377+each combination of `default`, `flag_value`, and whether378+the flag was passed on the command line.379+380+#### Boolean flags (`is_flag=True`, boolean `flag_value`)381+382+These are flags where `flag_value` is `True` or `False`.383+The `default` value is always passed through literally384+without any special substitution.385+386+| `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` |398+399+````{tip}400+For a negative flag that defaults to off, prefer the401+explicit pair form `--with-xyz/--without-xyz` over the402+single-flag `flag_value=False, default=True`:403+404+```python405+@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)406+```407 ````408 409+#### Boolean flag pairs (`--flag/--no-flag`)410+411+These use secondary option names to provide both an on and412+off switch. The `default` value is always literal.413+414+| `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` |420+421+#### Non-boolean feature switches (`flag_value` is a string, class, etc.)422+423+For these flags, `default=True` is a **special case**: it424+means "activate this flag by default" and resolves to the425+`flag_value`. All other `default` values are passed through426+literally.427+428+| `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"` |434+435+```{hint}436+¹: `default=True` is substituted with `flag_value`.437+```438+439+#### Feature switch groups (multiple flags sharing one variable)440+441+When multiple `flag_value` options target the same parameter442+name, `default=True` on one of them marks it as the default443+choice.444+445+| 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"` |450+451 ## Values from Environment Variables452 453 To pass in a value from a specific environment variable use `envvar`.454 133 unmodified linesadded:docs/standalone-apps.md+148 added
1+# Standalone Application with Briefcase2+3+[Briefcase](https://briefcase.beeware.org/) is a tool for packaging Python4+projects as standalone native applications. It can produce installers and5+executables for macOS, Windows, and Linux that do not require the user to6+install Python or any dependencies.7+8+- 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.12+13+This page outlines the basics of packaging a Click application with14+Briefcase. Be sure to read its15+[documentation](https://briefcase.beeware.org/en/stable/how-to/building/cli-apps/)16+and use ``briefcase --help`` to understand what features are available.17+18+## Installation19+20+Install Briefcase in the virtual environment:21+22+```console23+pip install briefcase24+```25+26+## Configuration27+28+Add a ``[tool.briefcase]`` section and a29+``[tool.briefcase.app.<app-name>]`` section to ``pyproject.toml``.30+Set ``console_app = true`` so Briefcase treats the project as a command31+line application rather than a GUI application.32+33+Given a Click application with the following project structure:34+35+```text36+hello-cli/37+ src/38+ hello_cli/39+ __init__.py40+ app.py41+ LICENSE42+ pyproject.toml43+```44+45+Where ``app.py`` contains a Click command:46+47+```python48+import click49+50+@click.command()51+@click.argument("name", default="World")52+@click.option("--count", default=1, help="Number of times to greet.")53+def main(name, count):54+ """Greet someone by NAME (default: World)."""55+ for _ in range(count):56+ click.echo(f"Hello, {name}!")57+```58+59+Add the following Briefcase configuration to ``pyproject.toml``:60+61+```toml62+[tool.briefcase]63+project_name = "Hello CLI"64+bundle = "com.example"65+version = "0.0.1"66+url = "https://example.com/hello-cli"67+license.file = "LICENSE"68+author = "Your Name"69+author_email = "you@example.com"70+71+[tool.briefcase.app.hello-cli]72+formal_name = "Hello CLI"73+description = "My first application"74+long_description = """More details about the app should go here.75+"""76+sources = [77+ "src/hello_cli",78+]79+console_app = true80+requires = [81+ "click",82+]83+```84+85+The key settings are:86+87+- ``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).92+93+## Entry Point94+95+Briefcase launches the application by running the package with96+``python -m <package>``, so a ``__main__.py`` file **must** exist in the97+package. Without it, Briefcase will not be able to start the application.98+99+Create ``__main__.py`` in the package directory and call the Click100+command:101+102+```python103+from hello_cli.app import main104+105+if __name__ == "__main__":106+ main()107+```108+109+## Running110+111+Use ``briefcase dev`` to run the application directly from the source112+tree. Pass command line arguments after ``--``:113+114+```console115+$ briefcase dev -- World116+Hello, World!117+$ briefcase dev -- World --count 2118+Hello, World!119+Hello, World!120+```121+122+## Building and Packaging123+124+To create a distributable executable, run the following commands:125+126+```console127+briefcase create128+briefcase build129+briefcase package130+```131+132+``briefcase create`` downloads a Python interpreter and installs133+dependencies into an isolated app bundle. ``briefcase build`` compiles134+the app, and ``briefcase package`` produces the final platform installer.135+136+On 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.139+140+Once installed, users can run the application directly from the terminal:141+142+```console143+$ hello-cli World144+Hello, World!145+$ hello-cli World --count 2146+Hello, World!147+Hello, World!148+```modified:docs/testing.md+48 added
194 unmodified lines195 196 Prompts will be emulated so they write the input data to197 the output stream as well. If hidden input is expected then this198 does not happen.199+200+## File Descriptors and Low-Level I/O201+202+{class}`CliRunner` captures output by replacing203+`sys.stdout` and `sys.stderr` with in-memory204+{class}`~io.BytesIO`-backed wrappers. This is205+Python-level redirection: calls to {func}`~click.echo`,206+{func}`print`, or `sys.stdout.write()` are captured, but207+the wrappers have no OS-level file descriptor.208+209+Code that calls `fileno()` on `sys.stdout` or210+`sys.stderr`, like {mod}`faulthandler`,211+{mod}`subprocess`, or C extensions, would normally crash212+with {exc}`io.UnsupportedOperation` inside213+{class}`CliRunner`.214+215+To avoid this, {class}`CliRunner` preserves the original216+stream's file descriptor and exposes it via `fileno()` on217+the replacement wrapper.218+219+This 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.225+226+This is the same trade-off that227+[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228+makes with its two capture modes:229+230+- `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.236+237+Rather than implementing a full `capfd`-style mechanism,238+{class}`CliRunner` takes the simpler path: expose the239+original `fd` so that standard library helpers keep240+working, while accepting that their output is not241+captured.242+243+```{versionchanged} 8.3.3244+`fileno()` on the redirected streams now returns the245+original stream's file descriptor instead of raising.246+```modified:src/click/core.py+24 added-5 removed
2889 unmodified lines2890 2891 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.2899+2900+ For example, with ``--upper/--lower`` feature switches where2901+ ``flag_value="upper"`` and ``default=True``, the default resolves2902+ to ``"upper"``.2903+2904+ .. 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.2911+2912+ .. 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)2918 2896- # 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 linesmodified:src/click/testing.py+59 added-6 removed
99 unmodified lines100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101 102 103 class _NamedTextIOWrapper(io.TextIOWrapper):104+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105+ that does not close its underlying buffer.106+107+ 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.112+113+ .. versionchanged:: 8.3.3114+ Added ``original_fd`` parameter and :meth:`fileno` override.115+ """116+117 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_fd130 131 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.135 136 .. versionadded:: 8.3.2137 """118- ...138 139+ def fileno(self) -> int:140+ """Return the file descriptor of the original stream, if one was141+ provided at construction time.142+143+ 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.147+148+ .. versionadded:: 8.3.3149+ """150+ if self._original_fd >= 0:151+ return self._original_fd152+ return super().fileno()153+154 @property155 def name(self) -> str:156 return self._name157 196 unmodified lines354 env = self.make_env(env)355 356 stream_mixer = StreamMixer()357 358+ # 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 -1368+369+ old_stdout_fd = _safe_fileno(old_stdout)370+ old_stderr_fd = _safe_fileno(old_stderr)371+372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )7 unmodified lines383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385 386 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 )393 394 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 )402 403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:268 unmodified linesmodified:src/click/utils.py+4 added-1 removed
55 unmodified lines56 return str(value)57 58 59 def 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.61+62+ :meta private:63+ """64 # Consider only the first paragraph.65 paragraph_end = help.find("\n\n")66 67 if paragraph_end != -1:563 unmodified linesmodified:tests/test_options.py+37 added-2 removed
1468 unmodified lines1469 ({"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 lines2500 assert result.exit_code == 02501 2502 2503 @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+)2518+def test_bool_flag_pair_default(runner, default, args, expected):2519+ """Boolean flag pairs pass ``default`` through literally.2520+2521+ Ensures ``default=True`` is not replaced by ``flag_value`` for boolean2522+ flags, and that ``default=None`` enables 3-state logic.2523+ """2524+2525+ @click.command()2526+ @click.option("--flag/--no-flag", default=default)2527+ def cli(flag):2528+ click.echo(repr(flag), nl=False)2529+2530+ result = runner.invoke(cli, args)2531+ assert result.exit_code == 02532+ assert result.output == repr(expected)2533+2534+2535+@pytest.mark.parametrize(2536 ("flag_type", "args", "expect_output"),2537 [2538 (str, [], "Default\n"),2539 (str, ["--theflag"], "FlagValue\n"),36 unmodified linesmodified:tests/test_termui.py+7 added-3 removed
876 unmodified lines877 # 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 linesmodified:tests/test_testing.py+26 added
1+import faulthandler2 import os3 import pdb4 import sys5 from io import BytesIO513 unmodified lines519 runner = CliRunner()520 runner.invoke(cli)521 522 assert pdb.Pdb.__init__ is original523+524+525+def test_faulthandler_enable(runner):526+ """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527+ ``io.UnsupportedOperation: fileno``.528+529+ ``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.532+533+ Reproduce:https://github.com/pallets/click/issues/2865534+ """535+536+ @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.")544+545+ result = runner.invoke(cli, ["--flag", True])546+ assert result.exit_code == 0, result.output547+ assert "Finished executing main function." in result.outputmodified:CHANGES.rst+10 added
22 unmodified lines23 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`37 38 Version 8.3.239 -------------40 1323 unmodified lines