Skip to content
Myr

arguments.rst

This file

Path

docs/arguments.rst

266 lines · 8.2 KiB

Last changed by

Merge stable into main (#2799)Rowlando13before adoptiond791537

History of this file

Take it

1.. _arguments:23Arguments4=========56.. currentmodule:: click78Arguments work similarly to :ref:`options <options>` but are positional.9They also only support a subset of the features of options due to their10syntactical nature. Click will also not attempt to document arguments for11you and wants you to :ref:`document them manually <documenting-arguments>`12in order to avoid ugly help pages.1314Basic Arguments15---------------1617The most basic option is a simple string argument of one value.  If no18type is provided, the type of the default value is used, and if no default19value is provided, the type is assumed to be :data:`STRING`.2021Example:2223.. click:example::2425    @click.command()26    @click.argument('filename')27    def touch(filename):28        """Print FILENAME."""29        click.echo(filename)3031And what it looks like:3233.. click:run::3435    invoke(touch, args=['foo.txt'])3637Variadic Arguments38------------------3940The second most common version is variadic arguments where a specific (or41unlimited) number of arguments is accepted.  This can be controlled with42the ``nargs`` parameter.  If it is set to ``-1``, then an unlimited number43of arguments is accepted.4445The value is then passed as a tuple.  Note that only one argument can be46set to ``nargs=-1``, as it will eat up all arguments.4748Example:4950.. click:example::5152    @click.command()53    @click.argument('src', nargs=-1)54    @click.argument('dst', nargs=1)55    def copy(src, dst):56        """Move file SRC to DST."""57        for fn in src:58            click.echo(f"move {fn} to folder {dst}")5960And what it looks like:6162.. click:run::6364    invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])6566Note that this is not how you would write this application.  The reason67for this is that in this particular example the arguments are defined as68strings.  Filenames, however, are not strings!  They might be on certain69operating systems, but not necessarily on all.  For better ways to write70this, see the next sections.7172.. admonition:: Note on Non-Empty Variadic Arguments7374   If you come from ``argparse``, you might be missing support for setting75   ``nargs`` to ``+`` to indicate that at least one argument is required.7677   This is supported by setting ``required=True``.  However, this should78   not be used if you can avoid it as we believe scripts should gracefully79   degrade into becoming noops if a variadic argument is empty.  The80   reason for this is that very often, scripts are invoked with wildcard81   inputs from the command line and they should not error out if the82   wildcard is empty.8384.. _file-args:8586File Arguments87--------------8889Since all the examples have already worked with filenames, it makes sense90to explain how to deal with files properly.  Command line tools are more91fun if they work with files the Unix way, which is to accept ``-`` as a92special file that refers to stdin/stdout.9394Click supports this through the :class:`click.File` type which95intelligently handles files for you.  It also deals with Unicode and bytes96correctly for all versions of Python so your script stays very portable.9798Example:99100.. click:example::101102    @click.command()103    @click.argument('input', type=click.File('rb'))104    @click.argument('output', type=click.File('wb'))105    def inout(input, output):106        """Copy contents of INPUT to OUTPUT."""107        while True:108            chunk = input.read(1024)109            if not chunk:110                break111            output.write(chunk)112113And what it does:114115.. click:run::116117    with isolated_filesystem():118        invoke(inout, args=['-', 'hello.txt'], input=['hello'],119               terminate_input=True)120        invoke(inout, args=['hello.txt', '-'])121122File Path Arguments123-------------------124125In the previous example, the files were opened immediately.  But what if126we just want the filename?  The naïve way is to use the default string127argument type. The :class:`Path` type has several checks available which raise nice128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.130131Example:132133.. click:example::134135    @click.command()136    @click.argument('filename', type=click.Path(exists=True))137    def touch(filename):138        """Print FILENAME if the file exists."""139        click.echo(click.format_filename(filename))140141And what it does:142143.. click:run::144145    with isolated_filesystem():146        with open('hello.txt', 'w') as f:147            f.write('Hello World!\n')148        invoke(touch, args=['hello.txt'])149        println()150        invoke(touch, args=['missing.txt'])151152153File Opening Safety154-------------------155156The :class:`FileType` type has one problem it needs to deal with, and that157is to decide when to open a file.  The default behavior is to be158"intelligent" about it.  What this means is that it will open stdin/stdout159and files opened for reading immediately.  This will give the user direct160feedback when a file cannot be opened, but it will only open files161for writing the first time an IO operation is performed by automatically162wrapping the file in a special wrapper.163164This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to165the constructor.  If the file is opened lazily, it will fail its first IO166operation by raising an :exc:`FileError`.167168Since files opened for writing will typically immediately empty the file,169the lazy mode should only be disabled if the developer is absolutely sure170that this is intended behavior.171172Forcing lazy mode is also very useful to avoid resource handling173confusion.  If a file is opened in lazy mode, it will receive a174``close_intelligently`` method that can help figure out if the file175needs closing or not.  This is not needed for parameters, but is176necessary for manually prompting with the :func:`prompt` function as you177do not know if a stream like stdout was opened (which was already open178before) or a real file that needs closing.179180Starting with Click 2.0, it is also possible to open files in atomic mode by181passing ``atomic=True``.  In atomic mode, all writes go into a separate182file in the same folder, and upon completion, the file will be moved over to183the original location.  This is useful if a file regularly read by other184users is modified.185186187.. _environment-variables:188189Environment Variables190---------------------191192Like options, arguments can also grab values from an environment variable.193Unlike options, however, this is only supported for explicitly named194environment variables.195196Example usage:197198.. click:example::199200    @click.command()201    @click.argument('src', envvar='SRC', type=click.File('r'))202    def echo(src):203        """Print value of SRC environment variable."""204        click.echo(src.read())205206And from the command line:207208.. click:run::209210    with isolated_filesystem():211        with open('hello.txt', 'w') as f:212            f.write('Hello World!')213        invoke(echo, env={'SRC': 'hello.txt'})214215In that case, it can also be a list of different environment variables216where the first one is picked.217218Generally, this feature is not recommended because it can cause the user219a lot of confusion.220221Option-Like Arguments222---------------------223224Sometimes, you want to process arguments that look like options.  For225instance, imagine you have a file named ``-foo.txt``.  If you pass this as226an argument in this manner, Click will treat it as an option.227228To solve this, Click does what any POSIX style command line script does,229and that is to accept the string ``--`` as a separator for options and230arguments.  After the ``--`` marker, all further parameters are accepted as231arguments.232233Example usage:234235.. click:example::236237    @click.command()238    @click.argument('files', nargs=-1, type=click.Path())239    def touch(files):240        """Print all FILES file names."""241        for filename in files:242            click.echo(filename)243244And from the command line:245246.. click:run::247248    invoke(touch, ['--', '-foo.txt', 'bar.txt'])249250If you don't like the ``--`` marker, you can set ignore_unknown_options to251True to avoid checking unknown options:252253.. click:example::254255    @click.command(context_settings={"ignore_unknown_options": True})256    @click.argument('files', nargs=-1, type=click.Path())257    def touch(files):258        """Print all FILES file names."""259        for filename in files:260            click.echo(filename)261262And from the command line:263264.. click:run::265266    invoke(touch, ['-foo.txt', 'bar.txt'])