Skip to content
Myr

arguments.rst

This file

Path

docs/arguments.rst

165 lines · 5.1 KiB

Last changed by

Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7

History of this file

Take it

1Arguments2=========34.. currentmodule:: click56Arguments work similar to options but are positional.  They also only7support a subset of the features of options due to their syntactical nature.8Click also will not attempt to document arguments for you and wants you to9document them manually to avoid ugly looking help pages.1011Basic Arguments12---------------1314The most basic option is a simple string argument of one value.  If no15type is provided the type of the default value is used.  If no default16value is provided the type is assumed to be :data:`STRING`.1718Example:1920.. click:example::2122    @click.command()23    @click.argument('filename')24    def touch(filename):25        click.echo(filename)2627And what it looks like:2829.. click:run::3031    invoke(touch, args=['foo.txt'])3233Variadic Arguments34------------------3536The second most common version is variadic arguments where a specific (or37unlimited) number of arguments is accepted.  This can be controlled with38the ``nargs`` parameter.  If it's set to ``-1`` then an unlimited number39of arguments is accepted.4041The value is then passed as a tuple.  Note that only one argument can be42set to ``nargs=-1`` as this will eat up all arguments.4344Example:4546.. click:example::4748    @click.command()49    @click.argument('src', nargs=-1)50    @click.argument('dst', nargs=1)51    def copy(src, dst):52        for fn in src:53            click.echo('move %s to folder %s' % (fn, dst))5455And what it looks like:5657.. click:run::5859    invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])6061.. admonition:: Note on Non-Empty Variadic Arguments6263   If you come from ``argparse`` you might be missing support for setting64   ``nargs`` to ``+`` to indicate that at least one argument is required.6566   Support for this is very intentionally not included as we believe67   scripts should gracefully degrate into becomming noops if a variadic68   argument is empty.  The reason for this is that very often scripts are69   invoked with wildcard inputs from the command line and they should not70   error out if the wildcard is empty.7172.. _file-args:7374File Arguments75--------------7677Since all the examples have already worked with file names it makes sense78to explain how to deal with files properly.  Command line tools are more79fun if they work with files the unix way which is to accept ``-`` as a80special file that refers to stdin/stdout.8182Click supports this through the :class:`click.File` type which83intelligently handles files for you.  It also deals with unicode and bytes84correctly for all versions of Python so your script stays very portable.8586Example:8788.. click:example::8990    @click.command()91    @click.argument('input', type=click.File('rb'))92    @click.argument('output', type=click.File('wb'))93    def inout(input, output):94        while True:95            chunk = input.read(1024)96            if not chunk:97                break98            output.write(chunk)99100And what it does:101102.. click:run::103104    with isolated_filesystem():105        invoke(inout, args=['-', 'hello.txt'], input=['hello'],106               terminate_input=True)107        invoke(inout, args=['hello.txt', '-'])108109File Opening Safety110-------------------111112The :class:`FileType` type has one problem it needs to deal with and that113is to decide when to open a file.  The default behavior is to be114"intelligent" about it.  What this means is that it will open stdin/stdout115and files opened for reading immediately.  This will directly give the116user feedback when a file cannot be opened.  But it will only open files117for writing the first time an IO operation is performed by wrapping the118file automatically in a special wrapper.119120This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to121the constructor.  If the file is openened lazily it will fail on first IO122operation by raising an :exc:`FileError`.123124Since files opened for writing will typically immediatley empty the file,125the lazy mode should really only be disabled if the developer is 100% sure126that this is intended behavior.127128Forcing on lazy mode is also very useful to avoid resource handling129confusion.  If a file is opened in lazy mode it will get a130``close_intelligently`` method that can help you figuring out if the file131needs closing or not.  This is not needed for parameters, but it is132necessary for manually prompting with the :func:`prompt` function as you133do not know if a stream like stdout was openend (which was already open134before) or a real file that needs closing.135136Environment Variables137---------------------138139Like options, arguments can also get values from an environment variable.140Unlike options however this is only supported for explicitly named141environment variables.142143Example usage:144145.. click:example::146147    @click.command()148    @click.argument('src', envvar='SRC', type=click.File('r'))149    def echo(src):150        click.echo(src.read())151152And from the command line:153154.. click:run::155156    with isolated_filesystem():157        with open('hello.txt', 'w') as f:158            f.write('Hello World!')159        invoke(echo, env={'SRC': 'hello.txt'})160161In that case it can also be a list of different environment variables162where the first one is picked.163164Generally this feature is not recommended because it can cause a lot of165confusion to the user.