Skip to content
Myr

parameters.rst

This file

Path

docs/parameters.rst

133 lines · 4.5 KiB

Last changed by

Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686

History of this file

Take it

1Parameters2==========34.. currentmodule:: click56Click supports two types of parameters for scripts: options and arguments.7There is generally some confusion among authors of command line scripts of8when to use which, so here is a quick overview of the differences.  As its9name indicates, an option is optional.  While arguments can be optional10within reason, they are much more restricted in how optional they can be.1112To help you decide between options and arguments, the recommendation is13to use arguments exclusively for things like going to subcommands or input14filenames / URLs, and have everything else be an option instead.1516Differences17-----------1819Arguments can do less than options.  The following features are only20available for options:2122*   automatic prompting for missing input23*   act as flags (boolean or otherwise)24*   option values can be pulled from environment variables, arguments can not25*   options are fully documented in the help page, arguments are not26    (this is intentional as arguments might be too specific to be27    automatically documented)2829On the other hand arguments, unlike options, can accept an arbitrary number30of arguments.  Options can strictly ever only accept a fixed number of31arguments (defaults to 1).3233Parameter Types34---------------3536Parameters can be of different types.  Types can be implemented with37different behavior and some are supported out of the box:3839``str`` / :data:`click.STRING`:40    The default parameter type which indicates unicode strings.4142``int`` / :data:`click.INT`:43    A parameter that only accepts integers.4445``float`` / :data:`click.FLOAT`:46    A parameter that only accepts floating point values.4748``bool`` / :data:`click.BOOL`:49    A parameter that accepts boolean values.  This is automatically used50    for boolean flags.  If used with string values ``1``, ``yes``, ``y``, ``t``51    and ``true`` convert to `True` and ``0``, ``no``, ``n``, ``f`` and ``false``52    convert to `False`.5354:data:`click.UUID`:55    A parameter that accepts UUID values.  This is not automatically56    guessed but represented as :class:`uuid.UUID`.5758.. autoclass:: File59   :noindex:6061.. autoclass:: Path62   :noindex:6364.. autoclass:: Choice65   :noindex:6667.. autoclass:: IntRange68   :noindex:6970.. autoclass:: FloatRange71  :noindex:7273Custom parameter types can be implemented by subclassing74:class:`click.ParamType`.  For simple cases, passing a Python function that75fails with a `ValueError` is also supported, though discouraged.7677.. _parameter_names:7879Parameter Names80---------------8182Parameters (both options and arguments) accept a number of positional arguments83which are passed to the command function as parameters. Each string with a84single dash is added as a short argument; each string starting with a double85dash as a long one.8687If a string is added without any dashes, it becomes the internal parameter name88which is also used as variable name.8990If all names for a parameter contain dashes, the internal name is generated91automatically by taking the longest argument and converting all dashes to92underscores.9394Examples:9596* For an option with ``('-f', '--foo-bar')``, the parameter name is `foo_bar`.97* For an option with ``('-x',)``, the parameter is `x`.98* For an option with ``('-f', '--filename', 'dest')``, the parameter name is  `dest`.99* For an arguments with ``(`foogle`)``, the parameter name is `foogle`. To100  provide a different human readable name for use in help text, see the section101  about :ref:`doc-meta-variables`.102103Implementing Custom Types104-------------------------105106To implement a custom type, you need to subclass the :class:`ParamType`107class.  Types can be invoked with or without context and parameter object,108which is why they need to be able to deal with this.109110The following code implements an integer type that accepts hex and octal111numbers in addition to normal integers, and converts them into regular112integers::113114    import click115116    class BasedIntParamType(click.ParamType):117        name = 'integer'118119        def convert(self, value, param, ctx):120            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('%s is not a valid integer' % value, param, ctx)128129    BASED_INT = BasedIntParamType()130131As you can see, a subclass needs to implement the :meth:`ParamType.convert`132method and optionally provide the :attr:`ParamType.name` attribute.  The133latter can be used for documentation purposes.