Skip to content
Myr

parameters.rst

This file

Path

docs/parameters.rst

137 lines · 4.4 KiB

Last changed by

Merge stable into main (#2799)Rowlando13before adoptiond791537

History of this file

Take it

1Parameters2==========34.. currentmodule:: click56Click supports only two types  of parameters for scripts (by design): options and arguments.78Options9----------------1011*   Are optional.12*   Recommended to use for everything except subcommands, urls, or files.13*   Can take a fixed number of arguments. The default is 1. They may be specified multiple times using :ref:`multiple-options`.14*   Are fully documented by the help page.15*   Have automatic prompting for missing input.16*   Can act as flags (boolean or otherwise).17*   Can be pulled from environment variables.1819Arguments20----------------2122*   Are optional with in reason, but not entirely so.23*   Recommended to use for subcommands, urls, or files.24*   Can take an arbitrary number of arguments.25*   Are not fully documented by the help page since they may be too specific to be automatically documented.  For more see :ref:`documenting-arguments`.26*   Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.2728.. _parameter_names:2930Parameter Names31---------------3233Parameters (options and arguments) have a name that will be used as34the Python argument name when calling the decorated function with35values.3637.. click:example::3839    @click.command()40    @click.argument('filename')41    @click.option('-t', '--times', type=int)42    def multi_echo(filename, times):43        """Print value filename multiple times."""44        for x in range(times):45            click.echo(filename)4647In 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`.48The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.4950And what it looks like when run:5152.. click:run::5354    invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5556Parameter Types57---------------5859The supported parameter types are:6061``str`` / :data:`click.STRING`:62    The default parameter type which indicates unicode strings.6364``int`` / :data:`click.INT`:65    A parameter that only accepts integers.6667``float`` / :data:`click.FLOAT`:68    A parameter that only accepts floating point values.6970``bool`` / :data:`click.BOOL`:71    A parameter that accepts boolean values. This is automatically used72    for boolean flags. The string values "1", "true", "t", "yes", "y",73    and "on" convert to ``True``. "0", "false", "f", "no", "n", and74    "off" convert to ``False``.7576:data:`click.UUID`:77    A parameter that accepts UUID values.  This is not automatically78    guessed but represented as :class:`uuid.UUID`.7980.. autoclass:: File81   :noindex:8283.. autoclass:: Path84   :noindex:8586.. autoclass:: Choice87   :noindex:8889.. autoclass:: IntRange90   :noindex:9192.. autoclass:: FloatRange93  :noindex:9495.. autoclass:: DateTime96   :noindex:9798How to Implement Custom Types99-------------------------------100101To 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.102103The following code implements an integer type that accepts hex and octal104numbers in addition to normal integers, and converts them into regular105integers.106107.. code-block:: python108109    import click110111    class BasedIntParamType(click.ParamType):112        name = "integer"113114        def convert(self, value, param, ctx):115            if isinstance(value, int):116                return value117118            try:119                if value[:2].lower() == "0x":120                    return int(value[2:], 16)121                elif value[:1] == "0":122                    return int(value, 8)123                return int(value, 10)124            except ValueError:125                self.fail(f"{value!r} is not a valid integer", param, ctx)126127    BASED_INT = BasedIntParamType()128129The :attr:`~ParamType.name` attribute is optional and is used for130documentation. Call :meth:`~ParamType.fail` if conversion fails. The131``param`` and ``ctx`` arguments may be ``None`` in some cases such as132prompts.133134Values from user input or the command line will be strings, but default135values and Python arguments may already be the correct type. The custom136type should check at the top if the value is already valid and pass it137through to support those cases.