Convert options docs to md.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Edward G · committed by Edward G · parent 1725157 · Browse files · 2 files·+451 added−411 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+451 added−411 removed
- other:+451 added−411 removed
Provenance
- Commit
d5cb0b8- Tree
8fd0ad8- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent
1725157
2 files changed+451 added−411 removed
added:docs/options.md+451 added
1+(options)=2+3+# Options4+5+```{eval-rst}6+.. currentmodule:: click7+```8+9+Adding options to commands can be accomplished with the {func}`option`10+decorator. At runtime the decorator invokes the {class}`Option` class. Options in Click are distinct from {ref}`positional arguments <arguments>`.11+12+Useful and often used kwargs are:13+14+- `default`: Passes a default.15+- `help`: Sets help message.16+- `nargs`: Sets the number of arguments.17+- `required`: Makes option required.18+- `type`: Sets {ref}`parameter type <parameter-types>`19+20+```{contents}21+:depth: 222+:local: true23+```24+25+## Option Decorator26+27+Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.28+29+```{eval-rst}30+.. click:example::31+32+ @click.command()33+ @click.option('--string-to-echo', 'string_to_echo')34+ def echo(string_to_echo):35+ click.echo(string_to_echo)36+37+38+.. click:run::39+40+ invoke(echo, args=['--help'])41+```42+43+However, if you don't pass in the function argument name, then Click will try to infer it. A simple way to name your option is by taking the function argument, adding two dashes to the front and converting underscores to dashes. In this case, Click will infer the function argument name correctly so you can add only the option name.44+45+```{eval-rst}46+.. click:example::47+48+ @click.command()49+ @click.option('--string-to-echo')50+ def echo(string_to_echo):51+ click.echo(string_to_echo)52+53+.. click:run::54+55+ invoke(echo, args=['--string-to-echo', 'Hi!'])56+```57+58+More formally, Click will try to infer the function argument name by:59+60+1. If a positional argument name does not have a prefix, it is chosen.61+2. If a positional argument name starts with with two dashes, the first one given is chosen.62+3. The first positional argument prefixed with one dash is chosen otherwise.63+64+The chosen positional argument is converted to lower case, up to two dashes are removed from the beginning, and other dashes are converted to underscores to get the function argument name.65+66+```{eval-rst}67+.. list-table:: Examples68+ :widths: 15 1069+ :header-rows: 170+71+ * - Decorator Arguments72+ - Function Name73+ * - ``"-f", "--foo-bar"``74+ - foo_bar75+ * - ``"-x"``76+ - x77+ * - ``"-f", "--filename", "dest"``78+ - dest79+ * - ``"--CamelCase"``80+ - camelcase81+ * - ``"-f", "-fb"``82+ - f83+ * - ``"--f", "--foo-bar"``84+ - f85+ * - ``"---f"``86+ - _f87+```88+89+## Basic Example90+91+A simple {class}`click.Option` takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is `str`.92+93+```{eval-rst}94+.. click:example::95+96+ @click.command()97+ @click.option('--text')98+ def print_this(text):99+ click.echo(text)100+101+102+.. click:run::103+104+ invoke(print_this, args=['--text=this'])105+106+ invoke(print_this, args=[])107+108+109+.. click:run::110+111+ invoke(print_this, args=['--help'])112+113+```114+115+## Setting a Default116+117+Instead of setting the `type`, you may set a default and Click will try to infer the type.118+119+```{eval-rst}120+.. click:example::121+122+ @click.command()123+ @click.option('--n', default=1)124+ def dots(n):125+ click.echo('.' * n)126+127+.. click:run::128+129+ invoke(dots, args=['--help'])130+```131+132+## Multi Value Options133+134+To make an option take multiple values, pass in `nargs`. Note only a fixed number of arguments is supported. The values are passed to the underlying function as a tuple.135+136+```{eval-rst}137+.. click:example::138+139+ @click.command()140+ @click.option('--pos', nargs=2, type=float)141+ def findme(pos):142+ a, b = pos143+ click.echo(f"{a} / {b}")144+145+.. click:run::146+147+ invoke(findme, args=['--pos', '2.0', '3.0'])148+149+```150+151+(tuple-type)=152+153+## Multi Value Options as Tuples154+155+:::{versionadded} 4.0156+:::157+158+As you can see that by using `nargs` set to a specific number each item in159+the resulting tuple is of the same type. This might not be what you want.160+Commonly you might want to use different types for different indexes in161+the tuple. For this you can directly specify a tuple as type:162+163+```{eval-rst}164+.. click:example::165+166+ @click.command()167+ @click.option('--item', type=(str, int))168+ def putitem(item):169+ name, id = item170+ click.echo(f"name={name} id={id}")171+172+173+And on the command line:174+175+.. click:run::176+177+ invoke(putitem, args=['--item', 'peter', '1338'])178+```179+180+By using a tuple literal as type, `nargs` gets automatically set to the181+length of the tuple and the {class}`click.Tuple` type is automatically182+used. The above example is thus equivalent to this:183+184+```{eval-rst}185+.. click:example::186+187+ @click.command()188+ @click.option('--item', nargs=2, type=click.Tuple([str, int]))189+ def putitem(item):190+ name, id = item191+ click.echo(f"name={name} id={id}")192+```193+194+(multiple-options)=195+196+## Multiple Options197+198+The multiple options format allows you to call the underlying function multiple times with one command line entry. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.199+200+```{eval-rst}201+.. click:example::202+203+ @click.command()204+ @click.option('--message', '-m', multiple=True)205+ def commit(message):206+ click.echo('\n'.join(message))207+208+.. click:run::209+210+ invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])211+```212+213+## Counting214+215+To count the occurrence of an option pass in `count=True`. If the option is not passed in, then the count is 0. Counting is commonly used for verbosity.216+217+```{eval-rst}218+.. click:example::219+220+ @click.command()221+ @click.option('-v', '--verbose', count=True)222+ def log(verbose):223+ click.echo(f"Verbosity: {verbose}")224+225+.. click:run::226+227+ invoke(log, args=[])228+ invoke(log, args=['-vvv'])229+```230+231+(option-boolean-flag)=232+233+## Boolean234+235+Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to `False` if the flag is not passed, and `True` if it is.236+237+```{eval-rst}238+.. click:example::239+240+ import sys241+242+ @click.command()243+ @click.option('--shout', is_flag=True)244+ def info(shout):245+ rv = sys.platform246+ if shout:247+ rv = rv.upper() + '!!!!111'248+ click.echo(rv)249+250+251+.. click:run::252+253+ invoke(info)254+ invoke(info, args=['--shout'])255+256+```257+258+To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`. Click always wants you to provide an enable259+and disable flag so that you can change the default later.260+261+```{eval-rst}262+.. click:example::263+264+ import sys265+266+ @click.command()267+ @click.option('--shout/--no-shout', default=False)268+ def info(shout):269+ rv = sys.platform270+ if shout:271+ rv = rv.upper() + '!!!!111'272+ click.echo(rv)273+274+.. click:run::275+276+ invoke(info)277+ invoke(info, args=['--shout'])278+ invoke(info, args=['--no-shout'])279+```280+281+If a forward slash(`/`) is contained in your option name already, you can split the parameters using `;`. In Windows `/` is commonly used as the prefix character.282+283+```{eval-rst}284+.. click:example::285+286+ @click.command()287+ @click.option('/debug;/no-debug')288+ def log(debug):289+ click.echo(f"debug={debug}")290+```291+292+:::{versionchanged} 6.0293+:::294+295+If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.296+297+```{eval-rst}298+.. click:example::299+300+ import sys301+302+ @click.command()303+ @click.option('--shout/--no-shout', ' /-N', default=False)304+ def info(shout):305+ rv = sys.platform306+ if shout:307+ rv = rv.upper() + '!!!!111'308+ click.echo(rv)309+310+.. click:run::311+312+ invoke(info, args=['--help'])313+```314+315+## Flag Value316+317+To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To set a default flag, set `default=True`. Setting flag values can be used to create patterns like this:318+319+```{eval-rst}320+.. click:example::321+322+ import sys323+324+ @click.command()325+ @click.option('--upper', 'transformation', flag_value='upper', default=True)326+ @click.option('--lower', 'transformation', flag_value='lower')327+ def info(transformation):328+ click.echo(getattr(sys.platform, transformation)())329+330+.. click:run::331+332+ invoke(info, args=['--help'])333+ invoke(info, args=['--upper'])334+ invoke(info, args=['--lower'])335+ invoke(info)336+```337+338+## Values from Environment Variables339+340+To pass in a value in from a specific environment variable use `envvar`.341+342+```{eval-rst}343+.. click:example::344+345+ @click.command()346+ @click.option('--username', envvar='USERNAME')347+ def greet(username):348+ click.echo(f"Hello {username}!")349+350+.. click:run::351+352+ invoke(greet, env={'USERNAME': 'john'})353+```354+355+If a list is passed to `envvar`, the first environment variable found is picked.356+357+```{eval-rst}358+.. click:example::359+360+ @click.command()361+ @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])362+ def greet(username):363+ click.echo(f"Hello {username}!")364+365+.. click:run::366+367+ invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})368+369+```370+371+## Multiple Options from Environment Values372+373+As options can accept multiple values, pulling in such values from374+environment variables (which are strings) is a bit more complex. The way375+Click solves this is by leaving it up to the type to customize this376+behavior. For both `multiple` and `nargs` with values other than377+`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to378+perform the splitting.379+380+The default implementation for all types is to split on whitespace. The381+exceptions to this rule are the {class}`File` and {class}`Path` types382+which both split according to the operating system's path splitting rules.383+On Unix systems like Linux and OS X, the splitting happens on384+every colon (`:`), and for Windows, splitting on every semicolon (`;`).385+386+```{eval-rst}387+.. click:example::388+389+ @click.command()390+ @click.option('paths', '--path', envvar='PATHS', multiple=True,391+ type=click.Path())392+ def perform(paths):393+ for path in paths:394+ click.echo(path)395+396+ if __name__ == '__main__':397+ perform()398+399+.. click:run::400+401+ import os402+ invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})403+```404+405+## Other Prefix Characters406+407+Click can deal with prefix characters besides `-` for options. Click can use408+`/`, `+` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.409+410+```{eval-rst}411+.. click:example::412+413+ @click.command()414+ @click.option('+w/-w')415+ def chmod(w):416+ click.echo(f"writable={w}")417+418+.. click:run::419+420+ invoke(chmod, args=['+w'])421+ invoke(chmod, args=['-w'])422+```423+424+There are special considerations for using `/` as prefix character, see {ref}`option-boolean-flag` for more.425+426+(optional-value)=427+428+## Optional Value429+430+Providing the value to an option can be made optional, in which case431+providing only the option's flag without a value will either show a432+prompt or use its `flag_value`.433+434+Setting `is_flag=False, flag_value=value` tells Click that the option435+can still be passed a value, but only if the flag is given the436+`flag_value`.437+438+```{eval-rst}439+.. click:example::440+441+ @click.command()442+ @click.option("--name", is_flag=False, flag_value="Flag", default="Default")443+ def hello(name):444+ click.echo(f"Hello, {name}!")445+446+.. click:run::447+448+ invoke(hello, args=[])449+ invoke(hello, args=["--name", "Value"])450+ invoke(hello, args=["--name"])451+```deleted:docs/options.rst-411 removed
1-.. _options:2-3-Options4-=========5-6-.. currentmodule:: click7-8-Adding options to commands can be accomplished with the :func:`option`9-decorator. At runtime the decorator invokes the :class:`Option` class. Options in Click are distinct from :ref:`positional arguments <arguments>`.10-11-Useful and often used kwargs are:12-13-* ``default``: Passes a default.14-* ``help``: Sets help message.15-* ``nargs``: Sets the number of arguments.16-* ``required``: Makes option required.17-* ``type``: Sets :ref:`parameter type <parameter-types>`18-19-.. contents::20- :depth: 221- :local:22-23-Option Decorator24------------------25-Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.26-27-.. click:example::28-29- @click.command()30- @click.option('--string-to-echo', 'string_to_echo')31- def echo(string_to_echo):32- click.echo(string_to_echo)33-34-.. click:run::35-36- invoke(echo, args=['--help'])37-38-However, if you don't pass in the function argument name, then Click will try to infer it. A simple way to name your option is by taking the function argument, adding two dashes to the front and converting underscores to dashes. In this case, Click will infer the function argument name correctly so you can add only the option name.39-40-.. click:example::41-42- @click.command()43- @click.option('--string-to-echo')44- def echo(string_to_echo):45- click.echo(string_to_echo)46-47-.. click:run::48-49- invoke(echo, args=['--string-to-echo', 'Hi!'])50-51-More formally, Click will try to infer the function argument name by:52-53-1. If a positional argument name does not have a prefix, it is chosen.54-2. If a positional argument name starts with with two dashes, the first one given is chosen.55-3. The first positional argument prefixed with one dash is chosen otherwise.56-57-The chosen positional argument is converted to lower case, up to two dashes are removed from the beginning, and other dashes are converted to underscores to get the function argument name.58-59-.. list-table:: Examples60- :widths: 15 1061- :header-rows: 162-63- * - Decorator Arguments64- - Function Name65- * - ``"-f", "--foo-bar"``66- - foo_bar67- * - ``"-x"``68- - x69- * - ``"-f", "--filename", "dest"``70- - dest71- * - ``"--CamelCase"``72- - camelcase73- * - ``"-f", "-fb"``74- - f75- * - ``"--f", "--foo-bar"``76- - f77- * - ``"---f"``78- - _f79-80-Basic Example81----------------82-A simple :class:`click.Option` takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is ``str``.83-84-.. click:example::85-86- @click.command()87- @click.option('--text')88- def print_this(text):89- click.echo(text)90-91-92-.. click:run::93-94- invoke(print_this, args=['--text=this'])95-96- invoke(print_this, args=[])97-98-.. click:run::99-100- invoke(print_this, args=['--help'])101-102-103-Setting a Default104----------------------------105-Instead of setting the ``type``, you may set a default and Click will try to infer the type.106-107-.. click:example::108-109- @click.command()110- @click.option('--n', default=1)111- def dots(n):112- click.echo('.' * n)113-114-.. click:run::115-116- invoke(dots, args=['--help'])117-118-Multi Value Options119--------------------120-121-To make an option take multiple values, pass in ``nargs``. Note only a fixed number of arguments is supported. The values are passed to the underlying function as a tuple.122-123-.. click:example::124-125- @click.command()126- @click.option('--pos', nargs=2, type=float)127- def findme(pos):128- a, b = pos129- click.echo(f"{a} / {b}")130-131-.. click:run::132-133- invoke(findme, args=['--pos', '2.0', '3.0'])134-135-136-.. _tuple-type:137-138-Multi Value Options as Tuples139------------------------------140-141-.. versionadded:: 4.0142-143-As you can see that by using `nargs` set to a specific number each item in144-the resulting tuple is of the same type. This might not be what you want.145-Commonly you might want to use different types for different indexes in146-the tuple. For this you can directly specify a tuple as type:147-148-.. click:example::149-150- @click.command()151- @click.option('--item', type=(str, int))152- def putitem(item):153- name, id = item154- click.echo(f"name={name} id={id}")155-156-And on the command line:157-158-.. click:run::159-160- invoke(putitem, args=['--item', 'peter', '1338'])161-162-By using a tuple literal as type, `nargs` gets automatically set to the163-length of the tuple and the :class:`click.Tuple` type is automatically164-used. The above example is thus equivalent to this:165-166-.. click:example::167-168- @click.command()169- @click.option('--item', nargs=2, type=click.Tuple([str, int]))170- def putitem(item):171- name, id = item172- click.echo(f"name={name} id={id}")173-174-.. _multiple-options:175-176-Multiple Options177------------------178-179-The multiple options format allows you to call the underlying function multiple times with one command line entry. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.180-181-.. click:example::182-183- @click.command()184- @click.option('--message', '-m', multiple=True)185- def commit(message):186- click.echo('\n'.join(message))187-188-.. click:run::189-190- invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])191-192-Counting193---------194-To count the occurrence of an option pass in ``count=True``. If the option is not passed in, then the count is 0. Counting is commonly used for verbosity.195-196-.. click:example::197-198- @click.command()199- @click.option('-v', '--verbose', count=True)200- def log(verbose):201- click.echo(f"Verbosity: {verbose}")202-203-.. click:run::204-205- invoke(log, args=[])206- invoke(log, args=['-vvv'])207-208-.. _option-boolean-flag:209-210-Boolean211-------------------------212-213-Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to ``False`` if the flag is not passed, and ``True`` if it is.214-215-.. click:example::216-217- import sys218-219- @click.command()220- @click.option('--shout', is_flag=True)221- def info(shout):222- rv = sys.platform223- if shout:224- rv = rv.upper() + '!!!!111'225- click.echo(rv)226-227-228-.. click:run::229-230- invoke(info)231- invoke(info, args=['--shout'])232-233-234-To implement this more explicitly, pass in on-option ``/`` off-option. Click will automatically set ``is_flag=True``. Click always wants you to provide an enable235-and disable flag so that you can change the default later.236-237-.. click:example::238-239- import sys240-241- @click.command()242- @click.option('--shout/--no-shout', default=False)243- def info(shout):244- rv = sys.platform245- if shout:246- rv = rv.upper() + '!!!!111'247- click.echo(rv)248-249-.. click:run::250-251- invoke(info)252- invoke(info, args=['--shout'])253- invoke(info, args=['--no-shout'])254-255-If a forward slash(``/``) is contained in your option name already, you can split the parameters using ``;``. In Windows ``/`` is commonly used as the prefix character.256-257-.. click:example::258-259- @click.command()260- @click.option('/debug;/no-debug')261- def log(debug):262- click.echo(f"debug={debug}")263-264-.. versionchanged:: 6.0265-266-If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.267-268-.. click:example::269-270- import sys271-272- @click.command()273- @click.option('--shout/--no-shout', ' /-N', default=False)274- def info(shout):275- rv = sys.platform276- if shout:277- rv = rv.upper() + '!!!!111'278- click.echo(rv)279-280-.. click:run::281-282- invoke(info, args=['--help'])283-284-Flag Value285----------------286-To have an flag pass a value to the underlying function set ``flag_value``. This automatically sets ``is_flag=True``. To set a default flag, set ``default=True``. Setting flag values can be used to create patterns like this:287-288-.. click:example::289-290- import sys291-292- @click.command()293- @click.option('--upper', 'transformation', flag_value='upper', default=True)294- @click.option('--lower', 'transformation', flag_value='lower')295- def info(transformation):296- click.echo(getattr(sys.platform, transformation)())297-298-.. click:run::299-300- invoke(info, args=['--help'])301- invoke(info, args=['--upper'])302- invoke(info, args=['--lower'])303- invoke(info)304-305-Values from Environment Variables306----------------------------------307-To pass in a value in from a specific environment variable use ``envvar``.308-309-.. click:example::310-311- @click.command()312- @click.option('--username', envvar='USERNAME')313- def greet(username):314- click.echo(f"Hello {username}!")315-316-.. click:run::317-318- invoke(greet, env={'USERNAME': 'john'})319-320-If a list is passed to ``envvar``, the first environment variable found is picked.321-322-.. click:example::323-324- @click.command()325- @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])326- def greet(username):327- click.echo(f"Hello {username}!")328-329-.. click:run::330-331- invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})332-333-334-Multiple Options from Environment Values335------------------------------------------336-337-As options can accept multiple values, pulling in such values from338-environment variables (which are strings) is a bit more complex. The way339-Click solves this is by leaving it up to the type to customize this340-behavior. For both ``multiple`` and ``nargs`` with values other than341-``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to342-perform the splitting.343-344-The default implementation for all types is to split on whitespace. The345-exceptions to this rule are the :class:`File` and :class:`Path` types346-which both split according to the operating system's path splitting rules.347-On Unix systems like Linux and OS X, the splitting happens on348-every colon (``:``), and for Windows, splitting on every semicolon (``;``).349-350-.. click:example::351-352- @click.command()353- @click.option('paths', '--path', envvar='PATHS', multiple=True,354- type=click.Path())355- def perform(paths):356- for path in paths:357- click.echo(path)358-359- if __name__ == '__main__':360- perform()361-362-.. click:run::363-364- import os365- invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})366-367-Other Prefix Characters368------------------------369-370-Click can deal with prefix characters besides ``-`` for options. Click can use371-``/``, ``+`` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.372-373-.. click:example::374-375- @click.command()376- @click.option('+w/-w')377- def chmod(w):378- click.echo(f"writable={w}")379-380-.. click:run::381-382- invoke(chmod, args=['+w'])383- invoke(chmod, args=['-w'])384-385-There are special considerations for using ``/`` as prefix character, see :ref:`option-boolean-flag` for more.386-387-.. _optional-value:388-389-Optional Value390---------------391-392-Providing the value to an option can be made optional, in which case393-providing only the option's flag without a value will either show a394-prompt or use its ``flag_value``.395-396-Setting ``is_flag=False, flag_value=value`` tells Click that the option397-can still be passed a value, but only if the flag is given the398-``flag_value``.399-400-.. click:example::401-402- @click.command()403- @click.option("--name", is_flag=False, flag_value="Flag", default="Default")404- def hello(name):405- click.echo(f"Hello, {name}!")406-407-.. click:run::408-409- invoke(hello, args=[])410- invoke(hello, args=["--name", "Value"])411- invoke(hello, args=["--name"])