arguments.rst
This file
Path
docs/arguments.rst
158 lines · 4.7 KiB
Last changed by
Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
History of this fileTake it
1.. _arguments:23Arguments4=========56.. currentmodule:: click78Arguments are:910* Are positional in nature.11* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12* :ref:`Documented manually <documenting-arguments>`.1314Useful and often used kwargs are:1516* ``default``: Passes a default.17* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.1819Basic Arguments20---------------2122A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.2324Example:2526.. click:example::2728 @click.command()29 @click.argument('filename')30 def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)3334And from the command line:3536.. click:run::3738 invoke(touch, args=['foo.txt'])394041An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.4243.. admonition:: Note on Required Arguments4445 It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.4647Multiple Arguments48-----------------------------------4950To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.5152.. click:example::5354 @click.command()55 @click.argument('src', nargs=1)56 @click.argument('dsts', nargs=-1)57 def copy(src: str, dsts: tuple[str, ...]):58 """Move file SRC to DST."""59 for destination in dsts:60 click.echo(f"Copy {src} to folder {destination}")6162And from the command line:6364.. click:run::6566 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])6768.. admonition:: Note on Handling Files6970 This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.7172Argument Escape Sequences73---------------------------7475If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.7677Example usage:7879.. click:example::8081 @click.command()82 @click.argument('files', nargs=-1, type=click.Path())83 def touch(files):84 """Print all FILES file names."""85 for filename in files:86 click.echo(filename)8788And from the command line:8990.. click:run::9192 invoke(touch, ['--', '-foo.txt', 'bar.txt'])9394If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:9596.. click:example::9798 @click.command(context_settings={"ignore_unknown_options": True})99 @click.argument('files', nargs=-1, type=click.Path())100 def touch(files):101 """Print all FILES file names."""102 for filename in files:103 click.echo(filename)104105And from the command line:106107.. click:run::108109 invoke(touch, ['-foo.txt', 'bar.txt'])110111112.. _environment-variables:113114Environment Variables115---------------------116117Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118119Checking one environment variable:120121.. click:example::122123 @click.command()124 @click.argument('src', envvar='SRC', type=click.File('r'))125 def echo(src):126 """Print value of SRC environment variable."""127 click.echo(src.read())128129And from the command line:130131.. click:run::132133 with isolated_filesystem():134 # Writing the file in the filesystem.135 with open('hello.txt', 'w') as f:136 f.write('Hello World!')137 invoke(echo, env={'SRC': 'hello.txt'})138139140Checking multiple environment variables:141142.. click:example::143144 @click.command()145 @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))146 def echo(src):147 """Print value of SRC environment variable."""148 click.echo(src.read())149150And from the command line:151152.. click:run::153154 with isolated_filesystem():155 # Writing the file in the filesystem.156 with open('hello.txt', 'w') as f:157 f.write('Hello World from second variable!')158 invoke(echo, env={'SRC_2': 'hello.txt'})