Skip to content
Myr

parameters.rst

This file

Path

docs/parameters.rst

139 lines · 4.4 KiB

Last changed by

Fill in a lot of missing command and group docs.Edward Gbefore adoptione2f2d84

History of this file

Take it

1.. _parameters:23Parameters4==========56.. currentmodule:: click78Click supports only two types  of parameters for scripts (by design): options and arguments.910Options11----------------1213*   Are optional.14*   Recommended to use for everything except subcommands, urls, or files.15*   Can take a fixed number of arguments. The default is 1. They may be specified multiple times using :ref:`multiple-options`.16*   Are fully documented by the help page.17*   Have automatic prompting for missing input.18*   Can act as flags (boolean or otherwise).19*   Can be pulled from environment variables.2021Arguments22----------------2324*   Are optional with in reason, but not entirely so.25*   Recommended to use for subcommands, urls, or files.26*   Can take an arbitrary number of arguments.27*   Are not fully documented by the help page since they may be too specific to be automatically documented.  For more see :ref:`documenting-arguments`.28*   Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.2930.. _parameter_names:3132Parameter Names33---------------3435Parameters (options and arguments) have a name that will be used as36the Python argument name when calling the decorated function with37values.3839.. click:example::4041    @click.command()42    @click.argument('filename')43    @click.option('-t', '--times', type=int)44    def multi_echo(filename, times):45        """Print value filename multiple times."""46        for x in range(times):47            click.echo(filename)4849In the above example the argument's name is ``filename``. The name must match the python arg name. To provide a different name for use in help text, see :ref:`doc-meta-variables`.50The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.5152And what it looks like when run:5354.. click:run::5556    invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5758Parameter Types59---------------6061The supported parameter types are:6263``str`` / :data:`click.STRING`:64    The default parameter type which indicates unicode strings.6566``int`` / :data:`click.INT`:67    A parameter that only accepts integers.6869``float`` / :data:`click.FLOAT`:70    A parameter that only accepts floating point values.7172``bool`` / :data:`click.BOOL`:73    A parameter that accepts boolean values. This is automatically used74    for boolean flags. The string values "1", "true", "t", "yes", "y",75    and "on" convert to ``True``. "0", "false", "f", "no", "n", and76    "off" convert to ``False``.7778:data:`click.UUID`:79    A parameter that accepts UUID values.  This is not automatically80    guessed but represented as :class:`uuid.UUID`.8182.. autoclass:: File83   :noindex:8485.. autoclass:: Path86   :noindex:8788.. autoclass:: Choice89   :noindex:9091.. autoclass:: IntRange92   :noindex:9394.. autoclass:: FloatRange95  :noindex:9697.. autoclass:: DateTime98   :noindex:99100How to Implement Custom Types101-------------------------------102103To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.104105The following code implements an integer type that accepts hex and octal106numbers in addition to normal integers, and converts them into regular107integers.108109.. code-block:: python110111    import click112113    class BasedIntParamType(click.ParamType):114        name = "integer"115116        def convert(self, value, param, ctx):117            if isinstance(value, int):118                return value119120            try:121                if value[:2].lower() == "0x":122                    return int(value[2:], 16)123                elif value[:1] == "0":124                    return int(value, 8)125                return int(value, 10)126            except ValueError:127                self.fail(f"{value!r} is not a valid integer", param, ctx)128129    BASED_INT = BasedIntParamType()130131The :attr:`~ParamType.name` attribute is optional and is used for132documentation. Call :meth:`~ParamType.fail` if conversion fails. The133``param`` and ``ctx`` arguments may be ``None`` in some cases such as134prompts.135136Values from user input or the command line will be strings, but default137values and Python arguments may already be the correct type. The custom138type should check at the top if the value is already valid and pass it139through to support those cases.