Skip to content
Myr

Merge stable into main (#3001)

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

authored by Rowlando13 · committed by GitHub · parents 91ac027, 565f36d · Browse files · 17 files+1234 added−936 removed
This commit

State

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

Diff stats

17 files+1234 added−936 removed

  • tests:+264 added−51 removed
  • other:+970 added−885 removed

17 files+1234 added−936 removed

added:docs/contrib.md+45 added
deleted:docs/contrib.rst-58 removed
1.. _contrib:23=============4click-contrib5=============67As the number of users of Click grows, more and more major feature requests are8made. To users it may seem reasonable to include those features with Click;9however, many of them are experimental or aren't practical to support10generically. Maintainers have to choose what is reasonable to maintain in Click11core.1213The click-contrib_ GitHub organization exists as a place to collect third-party14packages that extend Click's features. It is also meant to ease the effort of15searching for such extensions.1617Please note that the quality and stability of those packages may be different18than Click itself. While published under a common organization, they are still19separate from Click and the Pallets maintainers.202122Third-party projects23--------------------2425Other projects that extend Click's features are available outside of the26click-contrib_ organization.2728Some of the most popular and actively maintained are listed below:2930========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31Project Description Popularity Activity32========================================================== =========================================================================================== ================================================================================================= ======================================================================================================33`Typer <https://github.com/fastapi/typer>`_ Use Python type hints to create CLI apps. .. image:: https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square34 :alt: GitHub stars :alt: Last commit35`rich-click <https://github.com/ewels/rich-click>`_ Format help outputwith Rich. .. image:: https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square36 :alt: GitHub stars :alt: Last commit37`click-app <https://github.com/simonw/click-app>`_ Cookiecutter template for creating new CLIs. .. image:: https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square38 :alt: GitHub stars :alt: Last commit39`Cloup <https://github.com/janluke/cloup>`_ Adds option groups, constraints, command aliases, help themes, suggestions and more. .. image:: https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square40 :alt: GitHub stars :alt: Last commit41`Click Extra <https://github.com/kdeldycke/click-extra>`_ Cloup + colorful ``--help``, ``--config``, ``--show-params``, ``--verbosity`` options, etc. .. image:: https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square42 :alt: GitHub stars :alt: Last commit43========================================================== =========================================================================================== ================================================================================================= ======================================================================================================4445.. note::4647 To make it into the list above, a project:4849 - must be actively maintained (at least one commit in the last year)50 - must have a reasonable number of stars (at least 20)5152 If you have a project that meets these criteria, please open a pull request53 to add it to the list.5455 If a project is no longer maintained or does not meet the criteria above,56 please open a pull request to remove it from the list.5758.. _click-contrib: https://github.com/click-contrib/
added:docs/documentation.md+277 added
1# Help Pages23```{currentmodule} click4```56Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.78## Help Texts910Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.1112Simple example:1314```{eval-rst}15.. click:example::1617 @click.command()18 @click.argument('name')19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):23 if name:24 click.echo(f"Hello {name}!")25 else:26 click.echo("Hello!")2728.. click:run::29 invoke(hello, args=['--help'])30```3132## Command Short Help3334For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`:3536```{eval-rst}37.. click:example::3839 import click4041 @click.group()42 def cli():43 """A simple command line tool."""4445 @cli.command('init', short_help='init the repo')46 def init():47 """Initializes the repository."""4849.. click:run::50 invoke(cli, args=['--help'])51```5253## Command Epilog Help5455The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.5657```{eval-rst}58.. click:example::5960 import click6162 @click.command(63 epilog='See https://example.com for more details',64 )65 def init():66 """Initializes the repository."""6768.. click:run::69 invoke(init, args=['--help'])70```7172(documenting-arguments)=7374## Documenting Arguments7576{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77by name. This should then be done via the docstring.7879A brief example:8081```{eval-rst}82.. click:example::8384 @click.command()85 @click.argument('filename')86 def touch(filename):87 """Print FILENAME."""88 click.echo(filename)8990.. click:run::91 invoke(touch, args=['--help'])92```9394Or more explicitly:9596```{eval-rst}97.. click:example::9899 @click.command()100 @click.argument('filename')101 def touch(filename):102 """Print FILENAME.103104 FILENAME is the name of the file to check.105 """106 click.echo(filename)107108.. click:run::109 invoke(touch, args=['--help'])110```111112## Showing Defaults113114To control the appearance of defaults pass `show_default`.115116```{eval-rst}117.. click:example::118119 @click.command()120 @click.option('--n', default=1, show_default=False, help='number of dots')121 def dots(n):122 click.echo('.' * n)123124.. click:run::125 invoke(dots, args=['--help'])126```127128For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.129130```{eval-rst}131.. click:example::132133 @click.command()134 @click.option('--n', default=1, show_default=True)135 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")136 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")137 def dots(n, gr, br):138 if gr:139 click.echo('Hello world!')140 click.echo('.' * n)141 if br:142 click.echo('-' * n)143144.. click:run::145 invoke(dots, args=['--help'])146```147148## Click's Wrapping Behavior149150Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.151152```{eval-rst}153.. click:example::154155 import click156157 @click.command()158 def cli():159 """160 This is a very long paragraph and as you161 can see wrapped very early in the source text162 but will be rewrapped to the terminal width in163 the final output.164165 This is166 a paragraph167 that is compacted.168 """169170.. click:run::171 invoke(cli, args=['--help'])172```173174## Escaping Click's Wrapping175176Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text.177178Example:179180```{eval-rst}181.. click:example::182183 import click184185 @click.command()186 def cli():187 """First paragraph.188189 \b190 This is191 a paragraph192 without rewrapping.193194 And this is a paragraph195 that will be rewrapped again.196 """197198.. click:run::199 invoke(cli, args=['--help'])200```201202To change the rendering maximum width, pass `max_content_width` when calling the command.203204```bash205cli(max_content_width=120)206```207208## Truncating Help Texts209210Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker.211212Example:213214```{eval-rst}215.. click:example::216217 import click218219 @click.command()220 def cli():221 """First paragraph.222 \f223224 Words to not be included.225 """226227.. click:run::228 invoke(cli, args=['--help'])229```230231(doc-meta-variables)=232233## Placeholder / Meta Variable234235The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs.236237```{eval-rst}238.. click:example::239240 # This controls entry on the usage line.241 @click.command(options_metavar='[[options]]')242 @click.option('--count', default=1, help='number of greetings',243 metavar='<int>')244 @click.argument('name', metavar='<name>')245 def hello(name: str, count: int) -> None:246 """This script prints 'hello <name>' a total of <count> times."""247 for x in range(count):248 click.echo(f"Hello {name}!")249250# Example usage:251252.. click:run::253 invoke(hello, args=['--help'])254255```256257## Help Parameter Customization258259Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.260261This example changes the default parameters to `-h` and `--help`262instead of just `--help`:263264```{eval-rst}265.. click:example::266267 import click268269 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])270271 @click.command(context_settings=CONTEXT_SETTINGS)272 def cli():273 pass274275.. click:run::276 invoke(cli, ['-h'])277```
deleted:docs/documentation.rst-268 removed
1Help Pages2===================34.. currentmodule:: click56Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.78Help Texts9--------------1011Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.1213Simple example:1415.. click:example::1617 @click.command()18 @click.argument('name')19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):23 if name:24 click.echo(f"Hello {name}!")25 else:26 click.echo("Hello!")2728.. click:run::2930 invoke(hello, args=['--help'])313233Command Short Help34------------------3536For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with ``...``. The short help snippet can also be overridden with ``short_help``:3738.. click:example::3940 @click.group()41 def cli():42 """A simple command line tool."""4344 @cli.command('init', short_help='init the repo')45 def init():46 """Initializes the repository."""474849.. click:run::5051 invoke(cli, args=['--help'])5253Command Epilog Help54-------------------5556The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.5758.. click:example::5960 @click.command(61 epilog='See https://example.com for more details',62 )63 def init():64 """Initializes the repository."""656667.. click:run::6869 invoke(init, args=['--help'])7071.. _documenting-arguments:7273Documenting Arguments74----------------------7576:class:`click.argument` does not take a ``help`` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77by name. This should then be done via the docstring.7879A brief example:8081.. click:example::8283 @click.command()84 @click.argument('filename')85 def touch(filename):86 """Print FILENAME."""87 click.echo(filename)888990.. click:run::9192 invoke(touch, args=['--help'])9394Or more explicitly:9596.. click:example::9798 @click.command()99 @click.argument('filename')100 def touch(filename):101 """Print FILENAME.102103 FILENAME is the name of the file to check.104 """105 click.echo(filename)106107.. click:run::108109 invoke(touch, args=['--help'])110111112Showing Defaults113---------------------------114To control the appearance of defaults pass ``show_default``.115116.. click:example::117118 @click.command()119 @click.option('--n', default=1, show_default=False, help='number of dots')120 def dots(n):121 click.echo('.' * n)122123.. click:run::124125 invoke(dots, args=['--help'])126127For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128129.. click:example::130131 @click.command()132 @click.option('--n', default=1, show_default=True)133 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")134 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")135 def dots(n, gr, br):136 if gr:137 click.echo('Hello world!')138 click.echo('.' * n)139 if br:140 click.echo('-' * n)141142.. click:run::143144 invoke(dots, args=['--help'])145146147Click's Wrapping Behavior148----------------------------149Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.150151.. click:example::152153 @click.command()154 def cli():155 """156 This is a very long paragraph and as you157 can see wrapped very early in the source text158 but will be rewrapped to the terminal width in159 the final output.160161 This is162 a paragraph163 that is compacted.164 """165166.. click:run::167168 invoke(cli, args=['--help'])169170Escaping Click's Wrapping171---------------------------172Sometimes Click's wrapping can be a problem, such as when showing code examples where newlines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only ``\b`` . The ``\b`` is removed from the rendered help text.173174Example:175176.. click:example::177178 @click.command()179 def cli():180 """First paragraph.181182 \b183 This is184 a paragraph185 without rewrapping.186187 And this is a paragraph188 that will be rewrapped again.189 """190191192.. click:run::193194 invoke(cli, args=['--help'])195196To change the rendering maximum width, pass ``max_content_width`` when calling the command.197198.. code-block:: python199200 cli(max_content_width=120)201202203204Truncating Help Texts205---------------------206207Click gets :class:`Command` help text from the docstring. If you do not want to include part of the docstring, add the ``\f`` escape marker to have Click truncate the help text after the marker.208209Example:210211.. click:example::212213 @click.command()214 def cli():215 """First paragraph.216 \f217218 Words to not be included.219 """220221.. click:run::222223 invoke(cli, args=['--help'])224225.. _doc-meta-variables:226227Placeholder / Meta Variable228-----------------------------229230The default placeholder variable (`meta variable <https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments>`_) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the ``options_metavar`` and ``metavar`` kwargs.231232.. click:example::233234 # This controls entry on the usage line.235 @click.command(options_metavar='[[options]]')236 @click.option('--count', default=1, help='number of greetings',237 metavar='<int>')238 @click.argument('name', metavar='<name>')239 def hello(name: str, count: int) -> None:240 """This script prints 'hello <name>' a total of <count> times."""241 for x in range(count):242 click.echo(f"Hello {name}!")243244Example:245246.. click:run::247248 invoke(hello, args=['--help'])249250Help Parameter Customization251----------------------------252Help parameters are automatically added by Click for any command. The default is ``--help`` but can be override by the context setting :attr:`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter so if a command itself implements a parameter named ``help`` then the default help will not be run.253254This example changes the default parameters to ``-h`` and ``--help``255instead of just ``--help``:256257.. click:example::258259 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])260261 @click.command(context_settings=CONTEXT_SETTINGS)262 def cli():263 pass264265266.. click:run::267268 invoke(cli, ['-h'])
modified:docs/entry-points.rst+1 added-1 removed
1Packaging Entry Points2======================34It's recommended to write command line utilities as installable packages with5entry points instead telling users to run ``python hello.py``.5entry points instead of telling users to run ``python hello.py``.67A distribution package is a ``.whl`` file you install with pip or another Python8installer. You use a ``pyproject.toml`` file to describe the project and how it9is built into a package. You might upload this package to PyPI, or distribute it
78 unmodified lines
modified:docs/options.md+25 added
366 unmodified lines
367 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})368369```370371Variable names are:372 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).373 - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument.374375For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.376377The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not.378379Here are the rules used to parse environment variable values for flag options:380 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag381 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag382 - The presence of the environment variable without value is interpreted as deactivating the flag383 - Empty strings are interpreted as deactivating the flag384 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag385 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag386 - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above387 - Any other value is interpreted as deactivating the flag388389.. caution::390 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.391392 So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.393394Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.395396## Multiple Options from Environment Values397398As options can accept multiple values, pulling in such values from399environment variables (which are strings) is a bit more complex. The way
77 unmodified lines
added:docs/unicode-support.md+100 added
1# Unicode Support23```{currentmodule} click4```56Click has to take extra care to support Unicode text in different environments.78- The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some9 situations where this can break. The most common one is SSH connections to machines with different locales.1011 Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping12 surrogate escapes. This will not be fixed in Click itself!1314- Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain15 situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem16 when testing command-line applications.1718 This is not supported:1920 ```python21 sys.stdin = io.StringIO('Input here')22 sys.stdout = io.StringIO()23 ```2425 Instead you need to do this:2627 ```python28 input = 'Input here'29 in_stream = io.BytesIO(input.encode('utf-8'))30 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')31 out_stream = io.BytesIO()32 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')33 ```3435 Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access36 the buffer contents as the wrapper will not forward that method.3738- `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to39 discover the underlying binary stream.4041- `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not42 bytes.4344 This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the45 Unicode string will contain error bytes encoded as surrogate escapes.4647- When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or48 guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through49 the {func}`File` type even if the environment is misconfigured.5051## Surrogate Handling5253Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care.54The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operating55systems, its encoding handling is problematic.5657The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs will58refuse to work unless a Unicode locale is exported.5960If Click encounters such an environment it will prevent further execution to force you to set a locale. This is done61because Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicode62handling kicked in.6364If you see something like this error:6566```console67Traceback (most recent call last):68 ...69RuntimeError: Click will abort further execution because Python was70 configured to use ASCII as encoding for the environment. Consult71 https://click.palletsprojects.com/unicode-support/ for mitigation72 steps.73```7475You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problems76is different depending on which locale your computer is running in.7778For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`:7980```console81export LC_ALL=de_DE.utf-882export LANG=de_DE.utf-883```8485If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try86`C.UTF-8` as the locale:8788```console89export LC_ALL=C.UTF-890export LANG=C.UTF-891```9293On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales are94supported you can invoke `locale -a`.9596You need to export the values before you invoke your Python script.9798In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, which99changed the default assumption in unconfigured environments. This doesn't change the general issue that your locale may100be misconfigured.
deleted:docs/unicode-support.rst-112 removed
1Unicode Support2===============34.. currentmodule:: click56Click has to take extra care to support Unicode text in different7environments.89* The command line in Unix is traditionally bytes, not Unicode. While10 there are encoding hints, there are some situations where this can11 break. The most common one is SSH connections to machines with12 different locales.1314 Misconfigured environments can cause a wide range of Unicode15 problems due to the lack of support for roundtripping surrogate16 escapes. This will not be fixed in Click itself!1718* Standard input and output is opened in text mode by default. Click19 has to reopen the stream in binary mode in certain situations.20 Because there is no standard way to do this, it might not always21 work. Primarily this can become a problem when testing command-line22 applications.2324 This is not supported::2526 sys.stdin = io.StringIO('Input here')27 sys.stdout = io.StringIO()2829 Instead you need to do this::3031 input = 'Input here'32 in_stream = io.BytesIO(input.encode('utf-8'))33 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34 out_stream = io.BytesIO()35 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')3637 Remember in that case, you need to use ``out_stream.getvalue()``38 and not ``sys.stdout.getvalue()`` if you want to access the buffer39 contents as the wrapper will not forward that method.4041* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42 text-based. When Click needs a binary stream, it attempts to43 discover the underlying binary stream.4445* ``sys.argv`` is always text. This means that the native type for46 input values to the types in Click is Unicode, not bytes.4748 This causes problems if the terminal is incorrectly set and Python49 does not figure out the encoding. In that case, the Unicode string50 will contain error bytes encoded as surrogate escapes.5152* When dealing with files, Click will always use the Unicode file53 system API by using the operating system's reported or guessed54 filesystem encoding. Surrogates are supported for filenames, so it55 should be possible to open files through the :class:`File` type even56 if the environment is misconfigured.575859Surrogate Handling60------------------6162Click does all the Unicode handling in the standard library and is63subject to its behavior. Unicode requires extra care. The reason for64this is that the encoding detection is done in the interpreter, and on65Linux and certain other operating systems, its encoding handling is66problematic.6768The biggest source of frustration is that Click scripts invoked by init69systems, deployment tools, or cron jobs will refuse to work unless a70Unicode locale is exported.7172If Click encounters such an environment it will prevent further73execution to force you to set a locale. This is done because Click74cannot know about the state of the system once it's invoked and restore75the values before Python's Unicode handling kicked in.7677If you see something like this error::7879 Traceback (most recent call last):80 ...81 RuntimeError: Click will abort further execution because Python was82 configured to use ASCII as encoding for the environment. Consult83 https://click.palletsprojects.com/unicode-support/ for mitigation84 steps.8586You are dealing with an environment where Python thinks you are87restricted to ASCII data. The solution to these problems is different88depending on which locale your computer is running in.8990For instance, if you have a German Linux machine, you can fix the91problem by exporting the locale to ``de_DE.utf-8``::9293 export LC_ALL=de_DE.utf-894 export LANG=de_DE.utf-89596If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97On some newer Linux systems, you could also try ``C.UTF-8`` as the98locale::99100 export LC_ALL=C.UTF-8101 export LANG=C.UTF-8102103On some systems it was reported that ``UTF-8`` has to be written as104``UTF8`` and vice versa. To see which locales are supported you can105invoke ``locale -a``.106107You need to export the values before you invoke your Python script.108109In Python 3.7 and later you will no longer get a ``RuntimeError`` in110many cases thanks to :pep:`538` and :pep:`540`, which changed the111default assumption in unconfigured environments. This doesn't change the112general issue that your locale may be misconfigured.
added:docs/utils.md+390 added
1# Utilities23```{currentmodule} click4```56Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch7of addon functionality that is useful for writing command line utilities.89## Printing to Stdout1011The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or12function. The main difference is that it works the same in many different terminal environments.1314Example:1516```python17import click1819click.echo('Hello World!')20```2122It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23passing `nl=False`:2425```python26click.echo(b'\xe2\x98\x83', nl=False)27```2829Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support30unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode31characters (there are some limitations on the default font with regards to which characters can be displayed).3233```{versionadded} 6.034```3536Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37information see {doc}`wincmd`.3839```{versionadded} 3.040```4142You can also easily print to standard error by passing `err=True`:4344```python45click.echo('Hello World!', err=True)46```4748(ansi-colors)=4950## ANSI Colors5152```{versionadded} 2.053```5455The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).5657Primarily this means that:5859- Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.60- the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal61 API calls. This means that colors will work on Windows the same way they do on other operating systems.6263On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.6566For styling a string, the {func}`style` function can be used:6768```python69import click7071click.echo(click.style('Hello World!', fg='green'))72click.echo(click.style('Some more text', bg='blue', fg='white'))73click.echo(click.style('ATTENTION', blink=True, bold=True))74```7576The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:7778```python79click.secho('Hello World!', fg='green')80click.secho('Some more text', bg='blue', fg='white')81click.secho('ATTENTION', blink=True, bold=True)82```8384## Pager Support8586In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be87achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always88writes to stdout and, if possible, through a pager.8990Example:9192```python93@click.command()94def less():95 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))96```9798If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,99you can pass a generator (or generator function) instead of a string:100101```python102def _generate_output():103 for idx in range(50000):104 yield f"Line {idx}\n"105106@click.command()107def less():108 click.echo_via_pager(_generate_output())109```110111## Screen Clearing112113```{versionadded} 2.0114```115116To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does117what the name suggests: it clears the entire visible screen in a platform-agnostic way:118119```python120import click121click.clear()122```123124## Getting Characters from Terminal125126```{versionadded} 2.0127```128129Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and130will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead131read individual characters as they are being written.132133For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and134returns it as a Unicode character.135136Note that this function will always read from the terminal, even if stdin is instead a pipe.137138Example:139140```python141import click142143click.echo('Continue? [yn] ', nl=False)144c = click.getchar()145click.echo()146if c == 'y':147 click.echo('We will go on')148elif c == 'n':149 click.echo('Abort!')150else:151 click.echo('Invalid input :(')152```153154Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape155format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file156exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that157cannot be properly exited.158159## Waiting for Key Press160161```{versionadded} 2.0162```163164Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows165where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.166167In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the168terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP169(no operation instruction) if the script is not run interactively.170171Example:172173```python174import click175click.pause()176```177178## Launching Editors179180```{versionadded} 2.0181```182183Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line184input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the185editor without saving, the return value will be `None`, otherwise the entered text.186187Example usage:188189```python190import click191192def get_commit_message():193 MARKER = '# Everything below is ignored\n'194 message = click.edit('\n\n' + MARKER)195 if message is not None:196 return message.split(MARKER, 1)[0].rstrip('\n')197```198199Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the200return value is always `None`.201202Example usage:203204```python205import click206click.edit(filename='/etc/passwd')207```208209## Launching Applications210211```{versionadded} 2.0212```213214Click supports launching applications through {func}`launch`. This can be used to open the default application215associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition216to this, it can also launch the file manager and automatically select the provided file.217218Example usage:219220```python221click.launch("https://click.palletsprojects.com/")222click.launch("/my/downloaded/file.txt", locate=True)223```224225## Printing Filenames226227Because filenames might not be Unicode, formatting them can be a bit tricky.228229The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the230filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode231string.232233Example:234235```python236click.echo(f"Path: {click.format_filename(b'foo.txt')}")237```238239## Standard Streams240241For command line utilities, it's very important to get access to input and output streams reliably. Python generally242provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2432.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.244245Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce246consistent results with different Python versions and for a wide variety of terminal configurations.247248The end result is that these functions will always return a functional stream object (except in very odd cases; see249{doc}`/unicode-support`).250251Example:252253```python254import click255256stdin_text = click.get_text_stream('stdin')257stdout_binary = click.get_binary_stream('stdout')258```259260```{versionadded} 6.0261```262263Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more264information see {doc}`wincmd`.265266## Intelligent File Opening267268```{versionadded} 3.0269```270271Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`272function. It can intelligently open stdin/stdout as well as any other file.273274Example:275276```python277import click278279stdout = click.open_file('-', 'w')280test_file = click.open_file('test.txt', 'w')281```282283If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent284the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:285286```python287with click.open_file(filename, 'w') as f:288 f.write('Hello World!\n')289```290291## Finding Application Folders292293```{versionadded} 2.0294```295296Very often, you want to open a configuration file that belongs to your application. However, different operating systems297store these configuration files in different locations depending on their standards. Click provides a298{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application299depending on the OS.300301Example usage:302303```python304import os305import click306import ConfigParser307308APP_NAME = 'My Application'309def read_config():310cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')311parser = ConfigParser.RawConfigParser()312parser.read([cfg])313rv = {}314for section in parser.sections():315 for key, value in parser.items(section):316 rv[f"{section}.{key}"] = value317return rv318```319320## Showing Progress Bars321322Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some323progress about how long that will take. Click supports simple progress bar rendering for that through the324{func}`progressbar` function.325326```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).327```328329The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the330iterable it might take some time to do processing. So say you have a loop like this:331332```python333for user in all_the_users_to_process:334 modify_the_user(user)335```336337To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:338339```python340import click341342with click.progressbar(all_the_users_to_process) as bar:343 for user in bar:344 modify_the_user(user)345```346347Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The348calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the349length, you can explicitly provide it:350351```python352with click.progressbar(all_the_users_to_process,353 length=number_of_users) as bar:354 for user in bar:355 modify_the_user(user)356```357358Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render359correctly:360361```python362import time363364with click.progressbar([1, 2, 3]) as bar:365 for x in bar:366 print(f"sleep({x})...")367 time.sleep(x)368```369370Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:371372```python373with click.progressbar(all_the_users_to_process,374 label='Modifying user accounts',375 length=number_of_users) as bar:376 for user in bar:377 modify_the_user(user)378```379380Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you381need to specify the length (and no iterable), and use the update method on the context return value instead of iterating382directly over it:383384```python385with click.progressbar(length=total_size,386 label='Unzipping archive') as bar:387 for archive in zip_file:388 archive.extract()389 bar.update(archive.size)390```
deleted:docs/utils.rst-408 removed
1Utilities2=========34.. currentmodule:: click56Besides the functionality that Click provides to interface with argument7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.91011Printing to Stdout12------------------1314The most obvious helper is the :func:`echo` function, which in many ways15works like the Python ``print`` statement or function. The main difference is16that it works the same in many different terminal environments.1718Example::1920 import click2122 click.echo('Hello World!')2324It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::2627 click.echo(b'\xe2\x98\x83', nl=False)2829Last but not least :func:`echo` uses click's intelligent internal output30streams to stdout and stderr which support unicode output on the Windows31console. This means for as long as you are using `click.echo` you can32output unicode characters (there are some limitations on the default font33with regards to which characters can be displayed).3435.. versionadded:: 6.03637Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.04243You can also easily print to standard error by passing ``err=True``::4445 click.echo('Hello World!', err=True)464748.. _ansi-colors:4950ANSI Colors51-----------5253.. versionadded:: 2.05455The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.5758Primarily this means that:5960- Click's :func:`echo` function will automatically strip ANSI color codes61 if the stream is not connected to a terminal.62- the :func:`echo` function will transparently connect to the terminal on63 Windows and translate ANSI codes to terminal API calls. This means64 that colors will work on Windows the same way they do on other65 operating systems.6667On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.6970For styling a string, the :func:`style` function can be used::7172 import click7374 click.echo(click.style('Hello World!', fg='green'))75 click.echo(click.style('Some more text', bg='blue', fg='white'))76 click.echo(click.style('ATTENTION', blink=True, bold=True))7778The combination of :func:`echo` and :func:`style` is also available in79a single function called :func:`secho`::8081 click.secho('Hello World!', fg='green')82 click.secho('Some more text', bg='blue', fg='white')83 click.secho('ATTENTION', blink=True, bold=True)848586.. _colorama: https://pypi.org/project/colorama/8788Pager Support89-------------9091In some situations, you might want to show long texts on the terminal and92let a user scroll through it. This can be achieved by using the93:func:`echo_via_pager` function which works similarly to the :func:`echo`94function, but always writes to stdout and, if possible, through a pager.9596Example:9798.. click:example::99100 @click.command()101 def less():102 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103104If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:105106.. click:example::107 def _generate_output():108 for idx in range(50000):109 yield f"Line {idx}\n"110111 @click.command()112 def less():113 click.echo_via_pager(_generate_output())114115116Screen Clearing117---------------118119.. versionadded:: 2.0120121To clear the terminal screen, you can use the :func:`clear` function that122is provided starting with Click 2.0. It does what the name suggests: it123clears the entire visible screen in a platform-agnostic way:124125::126127 import click128 click.clear()129130131Getting Characters from Terminal132--------------------------------133134.. versionadded:: 2.0135136Normally, when reading input from the terminal, you would read from137standard input. However, this is buffered input and will not show up until138the line has been terminated. In certain circumstances, you might not want139to do that and instead read individual characters as they are being written.140141For this, Click provides the :func:`getchar` function which reads a single142character from the terminal buffer and returns it as a Unicode character.143144Note that this function will always read from the terminal, even if stdin145is instead a pipe.146147Example::148149 import click150151 click.echo('Continue? [yn] ', nl=False)152 c = click.getchar()153 click.echo()154 if c == 'y':155 click.echo('We will go on')156 elif c == 'n':157 click.echo('Abort!')158 else:159 click.echo('Invalid input :(')160161Note that this reads raw input, which means that things like arrow keys162will show up in the platform's native escape format. The only characters163translated are ``^C`` and ``^D`` which are converted into keyboard164interrupts and end of file exceptions respectively. This is done because165otherwise, it's too easy to forget about that and to create scripts that166cannot be properly exited.167168169Waiting for Key Press170---------------------171172.. versionadded:: 2.0173174Sometimes, it's useful to pause until the user presses any key on the175keyboard. This is especially useful on Windows where ``cmd.exe`` will176close the window at the end of the command execution by default, instead177of waiting.178179In click, this can be accomplished with the :func:`pause` function. This180function will print a quick message to the terminal (which can be181customized) and wait for the user to press a key. In addition to that,182it will also become a NOP (no operation instruction) if the script is not183run interactively.184185Example::186187 import click188 click.pause()189190191Launching Editors192-----------------193194.. versionadded:: 2.0195196Click supports launching editors automatically through :func:`edit`. This197is very useful for asking users for multi-line input. It will198automatically open the user's defined editor or fall back to a sensible199default. If the user closes the editor without saving, the return value200will be ``None``, otherwise the entered text.201202Example usage::203204 import click205206 def get_commit_message():207 MARKER = '# Everything below is ignored\n'208 message = click.edit('\n\n' + MARKER)209 if message is not None:210 return message.split(MARKER, 1)[0].rstrip('\n')211212Alternatively, the function can also be used to launch editors for files by213a specific filename. In this case, the return value is always `None`.214215Example usage::216217 import click218 click.edit(filename='/etc/passwd')219220221Launching Applications222----------------------223224.. versionadded:: 2.0225226Click supports launching applications through :func:`launch`. This can be227used to open the default application associated with a URL or filetype.228This can be used to launch web browsers or picture viewers, for instance.229In addition to this, it can also launch the file manager and automatically230select the provided file.231232Example usage::233234 click.launch("https://click.palletsprojects.com/")235 click.launch("/my/downloaded/file.txt", locate=True)236237238Printing Filenames239------------------240241Because filenames might not be Unicode, formatting them can be a bit242tricky.243244The way this works with click is through the :func:`format_filename`245function. It does a best-effort conversion of the filename to Unicode and246will never fail. This makes it possible to use these filenames in the247context of a full Unicode string.248249Example::250251 click.echo(f"Path: {click.format_filename(b'foo.txt')}")252253254Standard Streams255----------------256257For command line utilities, it's very important to get access to input and258output streams reliably. Python generally provides access to these259streams through ``sys.stdout`` and friends, but unfortunately, there are260API differences between 2.x and 3.x, especially with regards to how these261streams respond to Unicode and binary data.262263Because of this, click provides the :func:`get_binary_stream` and264:func:`get_text_stream` functions, which produce consistent results with265different Python versions and for a wide variety of terminal configurations.266267The end result is that these functions will always return a functional268stream object (except in very odd cases; see :doc:`/unicode-support`).269270Example::271272 import click273274 stdin_text = click.get_text_stream('stdin')275 stdout_binary = click.get_binary_stream('stdout')276277.. versionadded:: 6.0278279Click now emulates output streams on Windows to support unicode to the280Windows console through separate APIs. For more information see281:doc:`wincmd`.282283284Intelligent File Opening285------------------------286287.. versionadded:: 3.0288289Starting with Click 3.0 the logic for opening files from the :class:`File`290type is exposed through the :func:`open_file` function. It can291intelligently open stdin/stdout as well as any other file.292293Example::294295 import click296297 stdout = click.open_file('-', 'w')298 test_file = click.open_file('test.txt', 'w')299300If stdin or stdout are returned, the return value is wrapped in a special301file where the context manager will prevent the closing of the file. This302makes the handling of standard streams transparent and you can always use303it like this::304305 with click.open_file(filename, 'w') as f:306 f.write('Hello World!\n')307308309Finding Application Folders310---------------------------311312.. versionadded:: 2.0313314Very often, you want to open a configuration file that belongs to your315application. However, different operating systems store these configuration316files in different locations depending on their standards. Click provides317a :func:`get_app_dir` function which returns the most appropriate location318for per-user config files for your application depending on the OS.319320Example usage::321322 import os323 import click324 import ConfigParser325326 APP_NAME = 'My Application'327328 def read_config():329 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')330 parser = ConfigParser.RawConfigParser()331 parser.read([cfg])332 rv = {}333 for section in parser.sections():334 for key, value in parser.items(section):335 rv[f"{section}.{key}"] = value336 return rv337338339Showing Progress Bars340---------------------341342Sometimes, you have command line scripts that need to process a lot of data,343but you want to quickly show the user some progress about how long that344will take. Click supports simple progress bar rendering for that through345the :func:`progressbar` function.346347.. note::348349 If you find that you have requirements beyond what Click's progress350 bar supports, try using `tqdm`_.351352 .. _tqdm: https://tqdm.github.io/353354The basic usage is very simple: the idea is that you have an iterable that355you want to operate on. For each item in the iterable it might take some356time to do processing. So say you have a loop like this::357358 for user in all_the_users_to_process:359 modify_the_user(user)360361To hook this up with an automatically updating progress bar, all you need362to do is to change the code to this::363364 import click365366 with click.progressbar(all_the_users_to_process) as bar:367 for user in bar:368 modify_the_user(user)369370Click will then automatically print a progress bar to the terminal and371calculate the remaining time for you. The calculation of remaining time372requires that the iterable has a length. If it does not have a length373but you know the length, you can explicitly provide it::374375 with click.progressbar(all_the_users_to_process,376 length=number_of_users) as bar:377 for user in bar:378 modify_the_user(user)379380Note that :func:`progressbar` updates the bar *after* each iteration of the381loop. So code like this will render correctly::382383 import time384385 with click.progressbar([1, 2, 3]) as bar:386 for x in bar:387 print(f"sleep({x})...")388 time.sleep(x)389390Another useful feature is to associate a label with the progress bar which391will be shown preceding the progress bar::392393 with click.progressbar(all_the_users_to_process,394 label='Modifying user accounts',395 length=number_of_users) as bar:396 for user in bar:397 modify_the_user(user)398399Sometimes, one may need to iterate over an external iterator, and advance the400progress bar irregularly. To do so, you need to specify the length (and no401iterable), and use the update method on the context return value instead of402iterating directly over it::403404 with click.progressbar(length=total_size,405 label='Unzipping archive') as bar:406 for archive in zip_file:407 archive.extract()408 bar.update(archive.size)
modified:src/click/core.py+66 added-25 removed
2552 unmodified lines
2553 ) -> None:2554 if help:2555 help = inspect.cleandoc(help)25562557 default_is_missing = "default" not in attrs2557 super().__init__(2558 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2559 )2560
25 unmodified lines
2586 # used as a flag to indicate using prompt or flag_value.2587 self._flag_needs_value = self.prompt is not None and not self.prompt_required25882589 if is_flag is None:2590 # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2592 # Implicitly a flag because flag_value was set.2592 is_flag = True2593 # Not a flag, but when used as a flag it shows a prompt.2594 elif self._flag_needs_value:2595 # Not a flag, but when used as a flag it shows a prompt.2595 is_flag = False2597 else:2598 # Implicitly a flag because flag options were given.2599 is_flag = bool(self.secondary_opts)2596 # Implicitly a flag because flag options were given.2597 elif self.secondary_opts:2598 is_flag = True2599 elif is_flag is False and not self._flag_needs_value:2600 # Not a flag, and prompt is not enabled, can be used as a2601 # flag if flag_value is set.2602 self._flag_needs_value = flag_value is not None26032604 self.default: t.Any | t.Callable[[], t.Any]26052606 if is_flag:2607 # Set missing default for flags if not explicitly required or prompted.2607 if is_flag and default_is_missing and not self.required:2608 if multiple:2609 self.default = ()2610 else:2611 self.default = False2608 if self.default is None and not self.required and not self.prompt:2609 if multiple:2610 self.default = ()2611 else:2612 self.default = False26132613 if is_flag and flag_value is None:2614 flag_value = not self.default2614 if flag_value is None:2615 # A boolean flag presence in the command line is enough to set2616 # the value: to the default if it is not blank, or to True2617 # otherwise.2618 flag_value = self.default if self.default else True26192620 self.type: types.ParamType2621 if is_flag and type is None:2622 # Re-guess the type from the flag value instead of the2623 # default.2624 self.type = types.convert_type(None, flag_value)26252622 self.is_flag: bool = is_flag2623 self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2626 self.is_flag: bool = bool(is_flag)2627 self.is_bool_flag: bool = bool(2628 is_flag and isinstance(self.type, types.BoolParamType)2629 )2630 self.flag_value: t.Any = flag_value26312632 # Counting2633 self.count = count2634 if count:2635 if type is None:2636 self.type = types.IntRange(min=0)2631 if default_is_missing:2637 if self.default is None:2638 self.default = 026392640 self.allow_from_autoenv = allow_from_autoenv2641 self.help = help
281 unmodified lines
2923 # if we're the default one in which case we return the flag2924 # value as default.2925 if self.is_flag and not self.is_bool_flag:2926 for param in ctx.command.params:2921 if param.name == self.name and param.default:2922 return t.cast(Option, param).flag_value2927 if param.name == self.name and param.default is not None:2928 return t.cast(Option, param).default29292930 return None29312932 return super().get_default(ctx, call=call)
31 unmodified lines
2964 **prompt_kwargs,2965 )29662967 def resolve_envvar_value(self, ctx: Context) -> str | None:2968 """Find which environment variable to read for this option and return2969 its value.29702971 Returns the value of the environment variable if it exists, or ``None``2972 if it does not.29732974 .. caution::29752976 The raw value extracted from the environment is not normalized and2977 is returned as-is. Any normalization or reconciation with the2978 option's type should happen later.2979 """2980 rv = super().resolve_envvar_value(ctx)29812982 if rv is not None:2965 if self.is_flag and self.flag_value:2966 return str(self.flag_value)2983 return rv29842985 if (2986 self.allow_from_autoenv
8 unmodified lines
29952996 return None29972998 def value_from_envvar(self, ctx: Context) -> t.Any | None:2999 """Normalize the value from the environment variable, if it exists."""2983 rv: t.Any | None = self.resolve_envvar_value(ctx)3000 rv: str | None = self.resolve_envvar_value(ctx)30013002 if rv is None:3003 return None30042988 value_depth = (self.nargs != 1) + bool(self.multiple)3005 # Non-boolean flags are more liberal in what they accept. But a flag being a3006 # flag, its envvar value still needs to analyzed to determine if the flag is3007 # activated or not.3008 if self.is_flag and not self.is_bool_flag:3009 # If the flag_value is set and match the envvar value, return it3010 # directly.3011 if self.flag_value is not None and rv == self.flag_value:3012 return self.flag_value3013 # Analyze the envvar value as a boolean to know if the flag is3014 # activated or not.3015 return types.BoolParamType.str_to_bool(rv)30163017 # Split the envvar value if it is allowed to be repeated.3018 value_depth = (self.nargs != 1) + bool(self.multiple)3019 if value_depth > 0:2991 rv = self.type.split_envvar_value(rv)29923020 multi_rv = self.type.split_envvar_value(rv)3021 if self.multiple and self.nargs != 1:2994 rv = batch(rv, self.nargs)3022 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]30233024 return multi_rv30253026 return rv30273028 def consume_value(3029 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
10 unmodified lines
3040 else:3041 value = self.flag_value3042 source = ParameterSource.COMMANDLINE30433044 # A flag which is activated and has a flag_value set, should returns3045 # the latter, unless the value comes from the explicitly sets default.3046 elif (3047 self.is_flag3048 and value is True3049 and not self.is_bool_flag3050 and self.flag_value is not None3051 and source is not ParameterSource.DEFAULT3052 ):3053 value = self.flag_value30543055 elif (3056 self.multiple3057 and value is not None3058 and any(v is _flag_needs_value for v in value)3059 ):
117 unmodified lines
modified:src/click/types.py+57 added-13 removed
659 unmodified lines
660661class BoolParamType(ParamType):662 name = "boolean"663664 def convert(665 self, value: t.Any, param: Parameter | None, ctx: Context | None666 ) -> t.Any:667 if value in {False, True}:668 return bool(value)664 bool_states: dict[str, bool] = {665 "1": True,666 "0": False,667 "yes": True,668 "no": False,669 "true": True,670 "false": False,671 "on": True,672 "off": False,673 "t": True,674 "f": False,675 "y": True,676 "n": False,677 # Absence of value is considered False.678 "": False,679 }680 """A mapping of string values to boolean states.681670 norm = value.strip().lower()682 Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683 and extends it.684672 if norm in {"1", "true", "t", "yes", "y", "on"}:673 return True685 .. caution::686 String values are lower-cased, as the ``str_to_bool`` comparison function687 below is case-insensitive.688675 if norm in {"0", "false", "f", "no", "n", "off"}:676 return False689 .. warning::690 The mapping is not exhaustive, and does not cover all possible boolean strings691 representations. It will remains as it is to avoid endless bikeshedding.692678 self.fail(679 _("{value!r} is not a valid boolean.").format(value=value), param, ctx680 )693 Future work my be considered to make this mapping user-configurable from public694 API.695 """696697 @staticmethod698 def str_to_bool(value: str | bool) -> bool | None:699 """Convert a string to a boolean value.700701 If the value is already a boolean, it is returned as-is. If the value is a702 string, it is stripped of whitespaces and lower-cased, then checked against703 the known boolean states pre-defined in the `BoolParamType.bool_states` mapping704 above.705706 Returns `None` if the value does not match any known boolean state.707 """708 if isinstance(value, bool):709 return value710 return BoolParamType.bool_states.get(value.strip().lower())711712 def convert(713 self, value: t.Any, param: Parameter | None, ctx: Context | None714 ) -> bool:715 normalized = self.str_to_bool(value)716 if normalized is None:717 self.fail(718 _(719 "{value!r} is not a valid boolean. Recognized values: {states}"720 ).format(value=value, states=", ".join(sorted(self.bool_states))),721 param,722 ctx,723 )724 return normalized725726 def __repr__(self) -> str:727 return "BOOL"728729
480 unmodified lines
modified:tests/test_arguments.py-13 removed
196 unmodified lines
197 else:198 assert result.return_value == expect199200201def test_envvar_flag_value(runner):202 @click.command()203 # is_flag is implicitly true204 @click.option("--upper", flag_value="upper", envvar="UPPER")205 def cmd(upper):206 click.echo(upper)207 return upper208209 # For whatever value of the `env` variable, if it exists, the flag should be `upper`210 result = runner.invoke(cmd, env={"UPPER": "whatever"})211 assert result.output.strip() == "upper"212213201def test_nargs_envvar_only_if_values_empty(runner):202 @click.command()203 @click.argument("arg", envvar="X", nargs=-1)204 def cli(arg):
257 unmodified lines
modified:tests/test_basic.py+9 added-5 removed
220 unmodified lines
221 result = runner.invoke(cli, args, standalone_mode=False)222 assert result.return_value is expect223224225@pytest.mark.parametrize("default", [True, False])226@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])225@pytest.mark.parametrize(226 ("default", "args", "expect"),227 (228 (True, ["--f"], True),229 (True, [], True),230 (False, ["--f"], True),231 (False, [], False),232 ),233)234def test_boolean_flag(runner, default, args, expect):235 @click.command()236 @click.option("--f", is_flag=True, default=default)237 def cli(f):238 return f239233 if default:234 expect = not expect235240 result = runner.invoke(cli, args, standalone_mode=False)241 assert result.return_value is expect242243
415 unmodified lines
modified:tests/test_imports.py+16 added-15 removed
25 unmodified lines
26"""2728ALLOWED_IMPORTS = {29 "__future__",30 "weakref",31 "os",32 "struct",30 "codecs",31 "collections",32 "collections.abc",35 "sys",33 "configparser",34 "contextlib",35 "datetime",36 "enum",37 "errno",38 "fcntl",39 "functools",38 "stat",39 "re",40 "codecs",40 "gettext",41 "inspect",42 "itertools",42 "io",43 "itertools",44 "os",45 "re",46 "shutil",47 "stat",48 "struct",49 "sys",50 "threading",45 "errno",46 "fcntl",47 "datetime",48 "enum",49 "typing",51 "types",51 "gettext",52 "shutil",52 "typing",53 "weakref",54}5556if WIN:57 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])
14 unmodified lines
modified:tests/test_options.py+239 added-18 removed
245 unmodified lines
246 assert not result.exception247 assert result.output == "foo|bar\n"248249250def test_trailing_blanks_boolean_envvar(runner):250@pytest.mark.parametrize(251 ("name", "value", "expected"),252 (253 # Lower-cased variations of value.254 ("SHOUT", "true", True),255 ("SHOUT", "false", False),256 # Title-cased variations of value.257 ("SHOUT", "True", True),258 ("SHOUT", "False", False),259 # Upper-cased variations of value.260 ("SHOUT", "TRUE", True),261 ("SHOUT", "FALSE", False),262 # Random-cased variations of value.263 ("SHOUT", "TruE", True),264 ("SHOUT", "truE", True),265 ("SHOUT", "FaLsE", False),266 ("SHOUT", "falsE", False),267 # Extra spaces around the value.268 ("SHOUT", "true ", True),269 ("SHOUT", " true", True),270 ("SHOUT", " true ", True),271 ("SHOUT", "false ", False),272 ("SHOUT", " false", False),273 ("SHOUT", " false ", False),274 # Integer variations.275 ("SHOUT", "1", True),276 ("SHOUT", "0", False),277 # Alternative states.278 ("SHOUT", "t", True),279 ("SHOUT", "f", False),280 ("SHOUT", "y", True),281 ("SHOUT", "n", False),282 ("SHOUT", "yes", True),283 ("SHOUT", "no", False),284 ("SHOUT", "on", True),285 ("SHOUT", "off", False),286 # Blank value variations.287 ("SHOUT", None, False),288 ("SHOUT", "", False),289 ("SHOUT", " ", False),290 ("SHOUT", " ", False),291 # Variable names are not stripped of spaces and so don't match the292 # flag, which then naturraly takes its default value.293 ("SHOUT ", "True", False),294 ("SHOUT ", "False", False),295 (" SHOUT ", "True", False),296 (" SHOUT ", "False", False),297 # Same for random and reverse environment variable names: they are not298 # recognized by the option.299 ("RANDOM", "True", False),300 ("NO_SHOUT", "True", False),301 ("NO_SHOUT", "False", False),302 ),303)304def test_boolean_envvar_normalization(runner, name, value, expected):305 @click.command()306 @click.option("--shout/--no-shout", envvar="SHOUT")307 def cli(shout):308 click.echo(f"shout: {shout!r}")309256 result = runner.invoke(cli, [], env={"SHOUT": " true "})310 result = runner.invoke(cli, [], env={name: value})311 assert result.exit_code == 0258 assert result.output == "shout: True\n"312 assert result.output == f"shout: {expected}\n"313314315@pytest.mark.parametrize(316 ("name", "value"),317 (318 ("SHOUT", "tr ue"),319 ("SHOUT", "10"),320 ("SHOUT", "01"),321 ("SHOUT", "00"),322 ("SHOUT", "11"),323 ("SHOUT", "randomstring"),324 ("SHOUT", "None"),325 ),326)327def test_boolean_envvar_bad_values(runner, name, value):328 @click.command()329 @click.option("--shout/--no-shout", envvar="SHOUT")330 def cli(shout):331 click.echo(f"shout: {shout!r}")332333 result = runner.invoke(cli, [], env={name: value})334 assert result.exit_code == 2335 assert (336 f"Invalid value for '--shout': {value!r} is not a valid boolean."337 in result.output338 )339340341def test_multiple_default_help(runner):342 @click.command()343 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)344 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)
742 unmodified lines
1087 assert param.type is click.INT108810891090@pytest.mark.parametrize(1011 ("opts", "pass_flag", "expected"),1091 ("opt_params", "pass_flag", "expected"),1092 [1013 pytest.param({"type": bool}, False, "False"),1014 pytest.param({"type": bool}, True, "True"),1015 pytest.param({"type": bool, "default": True}, False, "True"),1016 pytest.param({"type": bool, "default": True}, True, "False"),1017 pytest.param({"type": click.BOOL}, False, "False"),1018 pytest.param({"type": click.BOOL}, True, "True"),1019 pytest.param({"type": click.BOOL, "default": True}, False, "True"),1020 pytest.param({"type": click.BOOL, "default": True}, True, "False"),1021 pytest.param({"type": str}, False, ""),1022 pytest.param({"type": str}, True, "True"),1093 # Effect of the presence/absence of flag depending on type1094 ({"type": bool}, False, False),1095 ({"type": bool}, True, True),1096 ({"type": click.BOOL}, False, False),1097 ({"type": click.BOOL}, True, True),1098 ({"type": str}, False, "False"),1099 ({"type": str}, True, "True"),1100 # Effects of default value1101 ({"type": bool, "default": True}, False, True),1102 ({"type": bool, "default": True}, True, True),1103 ({"type": bool, "default": False}, False, False),1104 ({"type": bool, "default": False}, True, True),1105 ({"type": bool, "default": None}, False, False),1106 ({"type": bool, "default": None}, True, True),1107 ({"type": click.BOOL, "default": True}, False, True),1108 ({"type": click.BOOL, "default": True}, True, True),1109 ({"type": click.BOOL, "default": False}, False, False),1110 ({"type": click.BOOL, "default": False}, True, True),1111 ({"type": click.BOOL, "default": None}, False, False),1112 ({"type": click.BOOL, "default": None}, True, True),1113 ({"type": str, "default": True}, False, "True"),1114 ({"type": str, "default": True}, True, "True"),1115 ({"type": str, "default": False}, False, "False"),1116 ({"type": str, "default": False}, True, "True"),1117 ({"type": str, "default": "foo"}, False, "foo"),1118 ({"type": str, "default": "foo"}, True, "foo"),1119 ({"type": str, "default": None}, False, "False"),1120 ({"type": str, "default": None}, True, "True"),1121 # Effects of flag_value1122 ({"type": bool, "flag_value": True}, False, False),1123 ({"type": bool, "flag_value": True}, True, True),1124 ({"type": bool, "flag_value": False}, False, False),1125 ({"type": bool, "flag_value": False}, True, False),1126 ({"type": bool, "flag_value": None}, False, False),1127 ({"type": bool, "flag_value": None}, True, True),1128 ({"type": click.BOOL, "flag_value": True}, False, False),1129 ({"type": click.BOOL, "flag_value": True}, True, True),1130 ({"type": click.BOOL, "flag_value": False}, False, False),1131 ({"type": click.BOOL, "flag_value": False}, True, False),1132 ({"type": click.BOOL, "flag_value": None}, False, False),1133 ({"type": click.BOOL, "flag_value": None}, True, True),1134 ({"type": str, "flag_value": True}, False, "False"),1135 ({"type": str, "flag_value": True}, True, "True"),1136 ({"type": str, "flag_value": False}, False, "False"),1137 ({"type": str, "flag_value": False}, True, "False"),1138 ({"type": str, "flag_value": "foo"}, False, "False"),1139 ({"type": str, "flag_value": "foo"}, True, "foo"),1140 ({"type": str, "flag_value": None}, False, "False"),1141 ({"type": str, "flag_value": None}, True, "True"),1142 # Not passing --foo returns the default value as-is1143 ({"type": bool, "default": True, "flag_value": True}, False, True),1144 ({"type": bool, "default": True, "flag_value": False}, False, True),1145 ({"type": bool, "default": False, "flag_value": True}, False, False),1146 ({"type": bool, "default": False, "flag_value": False}, False, False),1147 ({"type": bool, "default": None, "flag_value": True}, False, False),1148 ({"type": bool, "default": None, "flag_value": False}, False, False),1149 ({"type": str, "default": True, "flag_value": True}, False, "True"),1150 ({"type": str, "default": True, "flag_value": False}, False, "True"),1151 ({"type": str, "default": False, "flag_value": True}, False, "False"),1152 ({"type": str, "default": False, "flag_value": False}, False, "False"),1153 ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1154 ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1155 ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1156 ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1157 ({"type": str, "default": None, "flag_value": True}, False, "False"),1158 ({"type": str, "default": None, "flag_value": False}, False, "False"),1159 # Passing --foo returns the explicitly set flag_value1160 ({"type": bool, "default": True, "flag_value": True}, True, True),1161 ({"type": bool, "default": True, "flag_value": False}, True, False),1162 ({"type": bool, "default": False, "flag_value": True}, True, True),1163 ({"type": bool, "default": False, "flag_value": False}, True, False),1164 ({"type": bool, "default": None, "flag_value": True}, True, True),1165 ({"type": bool, "default": None, "flag_value": False}, True, False),1166 ({"type": str, "default": True, "flag_value": True}, True, "True"),1167 ({"type": str, "default": True, "flag_value": False}, True, "False"),1168 ({"type": str, "default": False, "flag_value": True}, True, "True"),1169 ({"type": str, "default": False, "flag_value": False}, True, "False"),1170 ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1171 ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1172 ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1173 ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1174 ({"type": str, "default": None, "flag_value": True}, True, "True"),1175 ({"type": str, "default": None, "flag_value": False}, True, "False"),1176 ],1177)1025def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1178def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1179 @click.command()1180 @click.option("--foo", is_flag=True, **opt_params)1181 def cmd(foo):1182 click.echo(repr(foo))11831184 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1185 assert result.output == f"{expected!r}\n"118611871188@pytest.mark.parametrize(1189 "opts",1190 [1191 {"type": bool, "default": "foo"},1192 {"type": bool, "flag_value": "foo"},1193 {"type": click.BOOL, "default": "foo"},1194 {"type": click.BOOL, "flag_value": "foo"},1195 ],1196)1197def test_invalid_flag_definition(runner, opts):1198 @click.command()1199 @click.option("--foo", is_flag=True, **opts)1200 def cmd(foo):1201 click.echo(foo)12021031 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1032 assert result.output == f"{expected}\n"1203 result = runner.invoke(cmd, ["--foo"])1204 assert (1205 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1206 in result.output1207 )120812091210@pytest.mark.parametrize(1211 ("flag_value", "envvar_value", "expected"),1212 [1213 # Envvar is set to false, so the flag default value is returned.1214 ("bar", "False", "False"),1215 # Same as above with alternative states and blank values.1216 ("bar", "0", "False"),1217 ("bar", "f", "False"),1218 ("bar", "", "False"),1219 # Envvar is set to true, so the flag_value is returned.1220 ("bar", "True", "bar"),1221 ("bar", "1", "bar"),1222 ("bar", "t", "bar"),1223 # So far we have the same cases as the test_flag_value_and_default1224 # test case. Now instead of passing a boolean-like value, let's use1225 # the flag_value as the envvar value.1226 ("bar", "bar", "bar"),1227 # flag_value is expected to be the exact same in the envvar for the flag to be1228 # activated.1229 ("bar", " bar ", "False"),1230 ("bar", "BAR", "False"),1231 ("bar", "random", "False"),1232 ("bar", "bar random", "False"),1233 ("bar", "random bar", "False"),1234 ("BAR", "BAR", "BAR"),1235 ("BAR", "bar", "False"),1236 (" bar ", " bar ", " bar "),1237 (" bar ", "bar", "False"),1238 (" bar ", "BAR", "False"),1239 ],1240)1241def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1242 """Ensure that flag_value is recognized by the envvar."""12431244 @click.command()1245 @click.option(1246 "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1247 )1248 def cmd(upper):1249 click.echo(repr(upper))12501251 result = runner.invoke(cmd, env={"UPPER": envvar_value})1252 assert result.exit_code == 01253 assert result.output == f"{expected!r}\n"125412551256@pytest.mark.parametrize(1257 ("option", "expected"),1258 [1259 # Not boolean flags1260 pytest.param(Option(["-a"], type=int), False, id="int option"),
6 unmodified lines
1267 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1268 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1269 ],1270)1050def test_is_bool_flag_is_correctly_set(option, expected):1271def test_bool_flag_auto_detection(option, expected):1272 assert option.is_bool_flag is expected127312741275@pytest.mark.parametrize(
87 unmodified lines
modified:CHANGES.rst+9 added
1.. currentmodule:: click23Version 8.2.24-------------56Unreleased78- 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`1112Version 8.2.113-------------1415Released 2025-05-20
1241 unmodified lines