Skip to content
Myr

Merge stable into main (#3029)

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

authored by Rowlando13 · committed by GitHub · parents a8b41c0, 1c68e53 · Browse files · 13 files+519 added−518 removed
This commit

State

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

Diff stats

13 files+519 added−518 removed

  • tests:+46 added−0 removed
  • other:+473 added−518 removed

13 files+519 added−518 removed

added:docs/quickstart.md+196 added
1# Quickstart23```{currentmodule} click4```56## Install78Install from PyPI:910```console11pip install click12```1314Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`.1516## Examples1718Some standalone examples of Click applications are packaged with Click. They are available in the19[examples folder](https://github.com/pallets/click/tree/main/examples) of the repo.2021- [inout](https://github.com/pallets/click/tree/main/examples/inout) : A very simple example of an application that can22 read from files and write to files and also accept input from stdin or write to stdout.23- [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24 performs custom validation of parameters in different ways.25- [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26 example.27- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28 colorama on Windows.29- [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements30 {ref}`aliases`.31- [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some32 {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.33- [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a34 Git-/Mercurial-like command line interface.35- [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements36 loading subcommands dynamically from a plugin folder.37- [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI38 helpers provided by click.3940## Basic Concepts - Creating a Command4142Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use43cases, but it's discouraged for high-level usage.4445A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just46decorating a function with this decorator will make it into a callable script:474849```{eval-rst}50.. click:example::51 import click5253 @click.command()54 def hello():55 click.echo('Hello World!')5657What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:5859.. click:example::60 if __name__ == '__main__':61 hello()6263And what it looks like:6465.. click:run::66 invoke(hello, args=[], prog_name='python hello.py')6768And the corresponding help page:6970.. click:run::71 invoke(hello, args=['--help'], prog_name='python hello.py')72```7374## Echoing7576Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is77that Click attempts to support different environments consistently and to be very robust even when the environment is78misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.7980What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured81instead of dying with a {exc}`UnicodeError`.8283The echo function also supports color and other styles in output. It will automatically remove styles if the output84stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.8586If you don't need this, you can also use the `print()` construct / function.8788## Nesting Commands8990Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an91example here is a script that implements two commands for managing databases:9293```{eval-rst}94.. click:example::95 @click.group()96 def cli():97 pass9899 @click.command()100 def initdb():101 click.echo('Initialized the database')102103 @click.command()104 def dropdb():105 click.echo('Dropped the database')106107 cli.add_command(initdb)108 cli.add_command(dropdb)109```110111As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`112object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.113114For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`115decorator instead. The above script can instead be written like this:116117```{eval-rst}118.. click:example::119 @click.group()120 def cli():121 pass122123 @cli.command()124 def initdb():125 click.echo('Initialized the database')126127 @cli.command()128 def dropdb():129 click.echo('Dropped the database')130131You would then invoke the :class:`Group` in your entry points or other invocations:132133.. click:example::134 if __name__ == '__main__':135 cli()136```137138## Registering Commands Later139140Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator141and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python142modules.143144```{code-block} python145 @click.command()146 def greet():147 click.echo("Hello, World!")148```149150```{code-block} python151 @click.group()152 def group():153 pass154155 group.add_command(greet)156```157158## Adding Parameters159160To add parameters, use the {func}`option` and {func}`argument` decorators:161162```{eval-rst}163.. click:example::164 @click.command()165 @click.option('--count', default=1, help='number of greetings')166 @click.argument('name')167 def hello(count, name):168 for x in range(count):169 click.echo(f"Hello {name}!")170171What it looks like:172173.. click:run::174 invoke(hello, args=['--help'], prog_name='python hello.py')175```176177## Switching to Entry Points178179In the code you wrote so far there is a block at the end of the file which looks like this:180`if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue181doing that, but a better way is to package your app with an entry point.182183There are two main (and many more) reasons for this:184185The first one is that installers automatically generate executable wrappers for Windows so your command line utilities186work on Windows too.187188The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be189activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a190virtualenv.191192Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing193applications as distributed packages.194195Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry196points.
deleted:docs/quickstart.rst-206 removed
1Quickstart2==========34.. currentmodule:: click56Install7----------------------8Install from PyPI::910 pip install click1112Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.1314Examples15-----------------------1617Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.1819* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`command-pipelines` . It chains together image processing instructions. Requires pillow.25* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.2829Basic Concepts - Creating a Command30-----------------------------------3132Click is based on declaring commands through decorators. Internally, there33is a non-decorator interface for advanced use cases, but it's discouraged34for high-level usage.3536A function becomes a Click command line tool by decorating it through37:func:`click.command`. At its simplest, just decorating a function38with this decorator will make it into a callable script:3940.. click:example::4142 import click4344 @click.command()45 def hello():46 click.echo('Hello World!')4748What's happening is that the decorator converts the function into a49:class:`Command` which then can be invoked::5051 if __name__ == '__main__':52 hello()5354And what it looks like:5556.. click:run::5758 invoke(hello, args=[], prog_name='python hello.py')5960And the corresponding help page:6162.. click:run::6364 invoke(hello, args=['--help'], prog_name='python hello.py')6566Echoing67-------6869Why does this example use :func:`echo` instead of the regular70:func:`print` function? The answer to this question is that Click71attempts to support different environments consistently and to be very72robust even when the environment is misconfigured. Click wants to be73functional at least on a basic level even if everything is completely74broken.7576What this means is that the :func:`echo` function applies some error77correction in case the terminal is misconfigured instead of dying with a78:exc:`UnicodeError`.7980The echo function also supports color and other styles in output. It81will automatically remove styles if the output stream is a file. On82Windows, colorama is automatically installed and used. See83:ref:`ansi-colors`.8485If you don't need this, you can also use the `print()` construct /86function.8788Nesting Commands89----------------9091Commands can be attached to other commands of type :class:`Group`. This92allows arbitrary nesting of scripts. As an example here is a script that93implements two commands for managing databases:9495.. click:example::9697 @click.group()98 def cli():99 pass100101 @click.command()102 def initdb():103 click.echo('Initialized the database')104105 @click.command()106 def dropdb():107 click.echo('Dropped the database')108109 cli.add_command(initdb)110 cli.add_command(dropdb)111112As you can see, the :func:`group` decorator works like the :func:`command`113decorator, but creates a :class:`Group` object instead which can be given114multiple subcommands that can be attached with :meth:`Group.add_command`.115116For simple scripts, it's also possible to automatically attach and create a117command by using the :meth:`Group.command` decorator instead. The above118script can instead be written like this:119120.. click:example::121122 @click.group()123 def cli():124 pass125126 @cli.command()127 def initdb():128 click.echo('Initialized the database')129130 @cli.command()131 def dropdb():132 click.echo('Dropped the database')133134You would then invoke the :class:`Group` in your entry points or other invocations::135136 if __name__ == '__main__':137 cli()138139140Registering Commands Later141--------------------------142143Instead of using the ``@group.command()`` decorator, commands can be144decorated with the plain ``@click.command()`` decorator and registered145with a group later with ``group.add_command()``. This could be used to146split commands into multiple Python modules.147148.. code-block:: python149150 @click.command()151 def greet():152 click.echo("Hello, World!")153154.. code-block:: python155156 @click.group()157 def group():158 pass159160 group.add_command(greet)161162163Adding Parameters164-----------------165166To add parameters, use the :func:`option` and :func:`argument` decorators:167168.. click:example::169170 @click.command()171 @click.option('--count', default=1, help='number of greetings')172 @click.argument('name')173 def hello(count, name):174 for x in range(count):175 click.echo(f"Hello {name}!")176177What it looks like:178179.. click:run::180181 invoke(hello, args=['--help'], prog_name='python hello.py')182183Switching to Entry Points184-------------------------185186In the code you wrote so far there is a block at the end of the file which187looks like this: ``if __name__ == '__main__':``. This is traditionally188how a standalone Python file looks like. With Click you can continue189doing that, but a better way is to package your app with an entry point.190191There are two main (and many more) reasons for this:192193The first one is that installers automatically generate executable194wrappers for Windows so your command line utilities work on Windows too.195196The second reason is that entry point scripts work with virtualenv on Unix197without the virtualenv having to be activated. This is a very useful198concept which allows you to bundle your scripts with all requirements into199a virtualenv.200201Click is perfectly equipped to work with that and in fact the rest of the202documentation will assume that you are writing applications as distributed203packages.204205Look at the :doc:`entry-points` chapter before reading the rest as the examples206assume that you will be using entry points.
added:docs/setuptools.md+7 added
deleted:docs/setuptools.rst-6 removed
1:orphan:23Setuptools Integration4======================56Moved to :doc:`entry-points`.
added:docs/shell-completion.md+249 added
1(shell-completion)=23# Shell Completion45```{currentmodule} click.shell_completion6```78Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9other shells too, and suggestions can be customized at multiple levels.1011Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12are only listed if at least a dash has been entered. Hidden commands and options are not shown.1314```console15$ repo <TAB><TAB>16clone commit copy delete setuser17$ repo clone -<TAB><TAB>18--deep --help --rev --shallow -r19```2021## Enabling Completion2223Completion is only available if a script is installed and invoked through an entry point, not through the `python`24command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will25put Click in completion mode.2627To enable shell completion, the user needs to register a special function with their shell. The exact script varies28depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to29`{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is30conventional but not strictly required for environment variable names to be in upper case. This convention helps31distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.3334Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.3536```{eval-rst}37.. tabs::3839 .. group-tab:: Bash4041 Add this to ``~/.bashrc``:4243 .. code-block:: bash4445 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"4647 .. group-tab:: Zsh4849 Add this to ``~/.zshrc``:5051 .. code-block:: zsh5253 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"5455 .. group-tab:: Fish5657 Add this to ``~/.config/fish/completions/foo-bar.fish``:5859 .. code-block:: fish6061 _FOO_BAR_COMPLETE=fish_source foo-bar | source6263 This is the same file used for the activation script method64 below. For Fish it's probably always easier to use that method.65```6667Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell68responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead69of time and distribute them with your program to save your users a step.7071```{eval-rst}72.. tabs::7374 .. group-tab:: Bash7576 Save the script somewhere.7778 .. code-block:: bash7980 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8182 Source the file in ``~/.bashrc``.8384 .. code-block:: bash8586 . ~/.foo-bar-complete.bash8788 .. group-tab:: Zsh8990 Save the script somewhere.9192 .. code-block:: bash9394 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh9596 Source the file in ``~/.zshrc``.9798 .. code-block:: bash99100 . ~/.foo-bar-complete.zsh101102 .. group-tab:: Fish103104 Save the script to ``~/.config/fish/completions/foo-bar.fish``:105106 .. code-block:: fish107108 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish109```110111After modifying the shell config, you need to start a new shell in order for the changes to be loaded.112113## Custom Type Completion114115When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide116shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.117Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to118indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.119120In this example, the type will suggest environment variables that start with the incomplete value.121122```python123class EnvVarType(ParamType):124 name = "envvar"125126 def shell_complete(self, ctx, param, incomplete):127 return [128 CompletionItem(name)129 for name in os.environ if name.startswith(incomplete)130 ]131132@click.command()133@click.option("--ev", type=EnvVarType())134def cli(ev):135 click.echo(os.environ[ev])136```137138## Overriding Value Completion139140Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141function is used instead of any completion provided by the type. It is passed 3 keyword arguments:142143- `ctx` - The current command context.144- `param` - The current parameter requesting completion.145- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered146 yet.147148It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.149150In this example, the command will suggest environment variables that start with the incomplete value.151152```python153def complete_env_vars(ctx, param, incomplete):154 return [k for k in os.environ if k.startswith(incomplete)]155156@click.command()157@click.argument("name", shell_complete=complete_env_vars)158def cli(name):159 click.echo(f"Name: {name}")160 click.echo(f"Value: {os.environ[name]}")161```162163## Adding Support for a Shell164165Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package166that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the167built-in implementations.168169Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When170Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or171{meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require172implementing some smaller parts.173174First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.175It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the176complete args and incomplete value. How it passes those values, and the format of the completion response from Click is177up to you.178179In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will180perform `%` formatting with the following variables:181182- `complete_func` - A safe name for the completion function defined in the script.183- `complete_var` - The environment variable name for passing the `{shell}_complete` instruction.184- `foo_bar` - The name of the executable being completed.185186The example code is for a made up shell "My Shell" or "mysh" for short.187188```python189from click.shell_completion import add_completion_class190from click.shell_completion import ShellComplete191192_mysh_source = """\193%(complete_func)s {194 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)195 # parse response and set completions somehow196}197call-on-complete %(foo_bar)s %(complete_func)s198"""199200@add_completion_class201class MyshComplete(ShellComplete):202 name = "mysh"203 source_template = _mysh_source204```205206Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and207incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains208the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method209must return a `(args, incomplete)` tuple.210211```python212import os213from click.parser import split_arg_string214215class MyshComplete(ShellComplete):216 ...217218 def get_completion_args(self):219 args = split_arg_string(os.environ["COMP_WORDS"])220221 if os.environ["COMP_PARTIAL"] == "1":222 incomplete = args.pop()223 return args, incomplete224225 return args, ""226```227228Finally, implement {meth}`~ShellComplete.format_completion`. This is called to format each {class}`CompletionItem` into a string. For example, the Bash implementation returns `f"{item.type},{item.value}` (it doesn't support help strings), and the Zsh implementation returns each part separated by a newline, replacing empty help with a `_` placeholder. This format is entirely up to what you parse with your completion script.229230The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example,231`file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click.232233```python234class MyshComplete(ShellComplete):235 ...236237 def format_completion(self, item):238 return f"{item.type}\t{item.value}"239```240241With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more242parts that can be overridden, but that probably isn't necessary.243244The activation instructions will again depend on how your shell works. Use the following to generate the completion245script, then load it into the shell somehow.246247```console248_FOO_BAR_COMPLETE=mysh_source foo-bar249```
deleted:docs/shell-completion.rst-291 removed
1.. currentmodule:: click.shell_completion23Shell Completion4================56Click provides tab completion support for Bash (version 4.4 and up),7Zsh, and Fish. It is possible to add support for other shells too, and8suggestions can be customized at multiple levels.910Shell completion suggests command names, option names, and values for11choice, file, and path parameter types. Options are only listed if at12least a dash has been entered. Hidden commands and options are not13shown.1415.. code-block:: text1617 $ repo <TAB><TAB>18 clone commit copy delete setuser19 $ repo clone -<TAB><TAB>20 --deep --help --rev --shallow -r212223Enabling Completion24-------------------2526Completion is only available if a script is installed and invoked27through an entry point, not through the ``python`` command. See28:doc:`entry-points`. Once the executable is installed, calling it with29a special environment variable will put Click in completion mode.3031To enable shell completion, the user needs to register a special32function with their shell. The exact script varies depending on the33shell you are using. Click will output it when called with34``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35the executable name in uppercase with dashes replaced by underscores.36It is conventional but not strictly required for environment variable37names to be in upper case. This convention helps distinguish environment38variables from regular shell variables and commands, making scripts39and configuration files more readable and easier to maintain. The40built-in shells are ``bash``, ``zsh``, and ``fish``.4142Provide your users with the following instructions customized to your43program name. This uses ``foo-bar`` as an example.4445.. tabs::4647 .. group-tab:: Bash4849 Add this to ``~/.bashrc``:5051 .. code-block:: bash5253 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"5455 .. group-tab:: Zsh5657 Add this to ``~/.zshrc``:5859 .. code-block:: zsh6061 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"6263 .. group-tab:: Fish6465 Add this to ``~/.config/fish/completions/foo-bar.fish``:6667 .. code-block:: fish6869 _FOO_BAR_COMPLETE=fish_source foo-bar | source7071 This is the same file used for the activation script method72 below. For Fish it's probably always easier to use that method.7374Using ``eval`` means that the command is invoked and evaluated every75time a shell is started, which can delay shell responsiveness. To speed76it up, write the generated script to a file, then source that. You can77generate the files ahead of time and distribute them with your program78to save your users a step.7980.. tabs::8182 .. group-tab:: Bash8384 Save the script somewhere.8586 .. code-block:: bash8788 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8990 Source the file in ``~/.bashrc``.9192 .. code-block:: bash9394 . ~/.foo-bar-complete.bash9596 .. group-tab:: Zsh9798 Save the script somewhere.99100 .. code-block:: bash101102 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103104 Source the file in ``~/.zshrc``.105106 .. code-block:: bash107108 . ~/.foo-bar-complete.zsh109110 .. group-tab:: Fish111112 Save the script to ``~/.config/fish/completions/foo-bar.fish``:113114 .. code-block:: fish115116 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117118After modifying the shell config, you need to start a new shell in order119for the changes to be loaded.120121122Custom Type Completion123----------------------124125When creating a custom :class:`~click.ParamType`, override its126:meth:`~click.ParamType.shell_complete` method to provide shell127completion for parameters with the type. The method must return a list128of :class:`~CompletionItem` objects. Besides the value, these objects129hold metadata that shell support might use. The built-in implementations130use ``type`` to indicate special handling for paths, and ``help`` for131shells that support showing a help string next to a suggestion.132133In this example, the type will suggest environment variables that start134with the incomplete value.135136.. code-block:: python137138 class EnvVarType(ParamType):139 name = "envvar"140141 def shell_complete(self, ctx, param, incomplete):142 return [143 CompletionItem(name)144 for name in os.environ if name.startswith(incomplete)145 ]146147 @click.command()148 @click.option("--ev", type=EnvVarType())149 def cli(ev):150 click.echo(os.environ[ev])151152153Overriding Value Completion154---------------------------155156Value completions for a parameter can be customized without a custom157type by providing a ``shell_complete`` function. The function is used158instead of any completion provided by the type. It is passed 3 keyword159arguments:160161- ``ctx`` - The current command context.162- ``param`` - The current parameter requesting completion.163- ``incomplete`` - The partial word that is being completed. May164 be an empty string if no characters have been entered yet.165166It must return a list of :class:`CompletionItem` objects, or as a167shortcut it can return a list of strings.168169In this example, the command will suggest environment variables that170start with the incomplete value.171172.. code-block:: python173174 def complete_env_vars(ctx, param, incomplete):175 return [k for k in os.environ if k.startswith(incomplete)]176177 @click.command()178 @click.argument("name", shell_complete=complete_env_vars)179 def cli(name):180 click.echo(f"Name: {name}")181 click.echo(f"Value: {os.environ[name]}")182183184Adding Support for a Shell185--------------------------186187Support can be added for shells that do not come built in. Be sure to188check PyPI to see if there's already a package that adds support for189your shell. This topic is very technical, you'll want to look at Click's190source to study the built-in implementations.191192Shell support is provided by subclasses of :class:`ShellComplete`193registered with :func:`add_completion_class`. When Click is invoked in194completion mode, it calls :meth:`~ShellComplete.source` to output the195completion script, or :meth:`~ShellComplete.complete` to output196completions. The base class provides default implementations that197require implementing some smaller parts.198199First, you'll need to figure out how your shell's completion system200works and write a script to integrate it with Click. It must invoke your201program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202``{shell}_complete`` and pass the complete args and incomplete value.203How it passes those values, and the format of the completion response204from Click is up to you.205206In your subclass, set :attr:`~ShellComplete.source_template` to the207completion script. The default implementation will perform ``%``208formatting with the following variables:209210- ``complete_func`` - A safe name for the completion function defined211 in the script.212- ``complete_var`` - The environment variable name for passing the213 ``{shell}_complete`` instruction.214- ``foo_bar`` - The name of the executable being completed.215216The example code is for a made up shell "My Shell" or "mysh" for short.217218.. code-block:: python219220 from click.shell_completion import add_completion_class221 from click.shell_completion import ShellComplete222223 _mysh_source = """\224 %(complete_func)s {225 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226 # parse response and set completions somehow227 }228 call-on-complete %(foo_bar)s %(complete_func)s229 """230231 @add_completion_class232 class MyshComplete(ShellComplete):233 name = "mysh"234 source_template = _mysh_source235236Next, implement :meth:`~ShellComplete.get_completion_args`. This must237get, parse, and return the complete args and incomplete value from the238completion script. For example, for the Bash implementation the239``COMP_WORDS`` env var contains the command line args as a string, and240the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241method must return a ``(args, incomplete)`` tuple.242243.. code-block:: python244245 import os246 from click.parser import split_arg_string247248 class MyshComplete(ShellComplete):249 ...250251 def get_completion_args(self):252 args = split_arg_string(os.environ["COMP_WORDS"])253254 if os.environ["COMP_PARTIAL"] == "1":255 incomplete = args.pop()256 return args, incomplete257258 return args, ""259260Finally, implement :meth:`~ShellComplete.format_completion`. This is261called to format each :class:`CompletionItem` into a string. For262example, the Bash implementation returns ``f"{item.type},{item.value}``263(it doesn't support help strings), and the Zsh implementation returns264each part separated by a newline, replacing empty help with a ``_``265placeholder. This format is entirely up to what you parse with your266completion script.267268The ``type`` value is usually ``plain``, but it can be another value269that the completion script can switch on. For example, ``file`` or270``dir`` can tell the shell to handle path completion, since the shell is271better at that than Click.272273.. code-block:: python274275 class MyshComplete(ShellComplete):276 ...277278 def format_completion(self, item):279 return f"{item.type}\t{item.value}"280281With those three things implemented, the new shell support is ready. In282case those weren't sufficient, there are more parts that can be283overridden, but that probably isn't necessary.284285The activation instructions will again depend on how your shell works.286Use the following to generate the completion script, then load it into287the shell somehow.288289.. code-block:: text290291 _FOO_BAR_COMPLETE=mysh_source foo-bar
modified:docs/utils.md+13 added-11 removed
87 unmodified lines
88writes to stdout and, if possible, through a pager.8990Example:9192```{eval-rst}92```python93@click.command()94def less():95 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))93.. click:example::94 @click.command()95 def less():96 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))97```9899If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100you can pass a generator (or generator function) instead of a string:101102```{eval-rst}101```python102def _generate_output():103 for idx in range(50000):104 yield f"Line {idx}\n"103.. click:example::104 def _generate_output():105 for idx in range(50000):106 yield f"Line {idx}\n"107106@click.command()107def less():108 click.echo_via_pager(_generate_output())108 @click.command()109 def less():110 click.echo_via_pager(_generate_output())111```112113## Screen Clearing114
278 unmodified lines
modified:src/click/core.py+1 added-1 removed
2680 unmodified lines
2681 return info_dict26822683 def get_error_hint(self, ctx: Context) -> str:2684 result = super().get_error_hint(ctx)2685 if self.show_envvar:2685 if self.show_envvar and self.envvar is not None:2686 result += f" (env var: '{self.envvar}')"2687 return result26882689 def _parse_decls(
489 unmodified lines
modified:tests/test_arguments.py+9 added
61 unmodified lines
62 assert result.exception is None63 assert result.output.splitlines() == ["name=peter id=1"]646566def test_nargs_mismatch_with_tuple_type():67 with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):6869 @click.command()70 @click.argument("test", type=(str, int), nargs=3)71 def cli(_):72 pass737475def test_nargs_err(runner):76 @click.command()77 @click.argument("x")78 def copy(x):
392 unmodified lines
modified:tests/test_options.py+37 added
675 unmodified lines
676 result = runner.invoke(cli)677 assert result.exit_code == 2678 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output679680 cli = click.Command(681 "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]682 )683 result = runner.invoke(cli)684 assert result.exit_code == 2685 assert "Error: Missing option '--foo'." in result.output686687688def test_case_insensitive_choice(runner):689 @click.command()690 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))691 def cmd(foo):
760 unmodified lines
1452 pass14531454 with pytest.warns(UserWarning):1455 runner.invoke(cli, [])145614571458@pytest.mark.parametrize(1459 ("multiple", "nargs", "default", "expected_message"),1460 [1461 (1462 False, # multiple1463 2, # nargs1464 42, # default (not a list)1465 "'default' must be a list when 'nargs' != 1.",1466 ),1467 (1468 True, # multiple1469 2, # nargs1470 [1471 "test string which is not a list in the list"1472 ], # default (list of non-lists)1473 "'default' must be a list of lists when 'multiple' is true"1474 " and 'nargs' != 1.",1475 ),1476 ],1477)1478def test_default_type_error_raises(multiple, nargs, default, expected_message):1479 with pytest.raises(ValueError, match=expected_message):1480 click.Option(1481 ["--test"],1482 multiple=multiple,1483 nargs=nargs,1484 default=default,1485 )
modified:CHANGES.rst+5 added-1 removed
1 unmodified line
23Version 8.2.24-------------56Unreleased6Released 2025-07-3178- Fix reconciliation of `default`, `flag_value` and `type` parameters for9 flag options, as well as parsing and normalization of environment variables.10 :issue:`2952` :pr:`2956`
3 unmodified lines
14- Use the value of ``Enum`` choices to render their default value in help15 screen. Refs :issue:`2911` :pr:`3004`16- Fix completion for the Z shell (``zsh``) for completion items containing17 colons. :issue:`2703` :pr:`2846`18- Don't include envvar in error hint when not configured. :issue:`2971` :pr:`2972`19- Fix a rare race in ``click.testing.StreamMixer``'s finalization that manifested20 as a ``ValueError`` on close in a multi-threaded test session.21 :issue:`2993` :pr:`2991`2223Version 8.2.124-------------25
1242 unmodified lines
modified:pyproject.toml+1 added-1 removed
1[project]2name = "click"3version = "8.2.1"3version = "8.2.2"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
201 unmodified lines
modified:uv.lock+1 added-1 removed
137 unmodified lines
138]139140[[package]]141name = "click"142version = "8.2.1"142version = "8.2.2"143source = { editable = "." }144dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146]
1076 unmodified lines