Skip to content
Myr

arguments.rst

This file

Path

docs/arguments.rst

269 lines · 8.5 KiB

Last changed by

Not known.

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.  However, remember that Click is Unicode-based, so the string128will always be a Unicode value.  Unfortunately, filenames can be Unicode or129bytes depending on which operating system is being used.  As such, the type130is insufficient.131132Instead, you should be using the :class:`Path` type, which automatically133handles this ambiguity.  Not only will it return either bytes or Unicode134depending on what makes more sense, but it will also be able to do some135basic checks for you such as existence checks.136137Example:138139.. click:example::140141    @click.command()142    @click.argument('filename', type=click.Path(exists=True))143    def touch(filename):144        """Print FILENAME if the file exists."""145        click.echo(click.format_filename(filename))146147And what it does:148149.. click:run::150151    with isolated_filesystem():152        with open('hello.txt', 'w') as f:153            f.write('Hello World!\n')154        invoke(touch, args=['hello.txt'])155        println()156        invoke(touch, args=['missing.txt'])157158159File Opening Safety160-------------------161162The :class:`FileType` type has one problem it needs to deal with, and that163is to decide when to open a file.  The default behavior is to be164"intelligent" about it.  What this means is that it will open stdin/stdout165and files opened for reading immediately.  This will give the user direct166feedback when a file cannot be opened, but it will only open files167for writing the first time an IO operation is performed by automatically168wrapping the file in a special wrapper.169170This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to171the constructor.  If the file is opened lazily, it will fail its first IO172operation by raising an :exc:`FileError`.173174Since files opened for writing will typically immediately empty the file,175the lazy mode should only be disabled if the developer is absolutely sure176that this is intended behavior.177178Forcing lazy mode is also very useful to avoid resource handling179confusion.  If a file is opened in lazy mode, it will receive a180``close_intelligently`` method that can help figure out if the file181needs closing or not.  This is not needed for parameters, but is182necessary for manually prompting with the :func:`prompt` function as you183do not know if a stream like stdout was opened (which was already open184before) or a real file that needs closing.185186Starting with Click 2.0, it is also possible to open files in atomic mode by187passing ``atomic=True``.  In atomic mode, all writes go into a separate188file in the same folder, and upon completion, the file will be moved over to189the original location.  This is useful if a file regularly read by other190users is modified.191192Environment Variables193---------------------194195Like options, arguments can also grab values from an environment variable.196Unlike options, however, this is only supported for explicitly named197environment variables.198199Example usage:200201.. click:example::202203    @click.command()204    @click.argument('src', envvar='SRC', type=click.File('r'))205    def echo(src):206        """Print value of SRC environment variable."""207        click.echo(src.read())208209And from the command line:210211.. click:run::212213    with isolated_filesystem():214        with open('hello.txt', 'w') as f:215            f.write('Hello World!')216        invoke(echo, env={'SRC': 'hello.txt'})217218In that case, it can also be a list of different environment variables219where the first one is picked.220221Generally, this feature is not recommended because it can cause the user222a lot of confusion.223224Option-Like Arguments225---------------------226227Sometimes, you want to process arguments that look like options.  For228instance, imagine you have a file named ``-foo.txt``.  If you pass this as229an argument in this manner, Click will treat it as an option.230231To solve this, Click does what any POSIX style command line script does,232and that is to accept the string ``--`` as a separator for options and233arguments.  After the ``--`` marker, all further parameters are accepted as234arguments.235236Example usage:237238.. click:example::239240    @click.command()241    @click.argument('files', nargs=-1, type=click.Path())242    def touch(files):243        """Print all FILES file names."""244        for filename in files:245            click.echo(filename)246247And from the command line:248249.. click:run::250251    invoke(touch, ['--', '-foo.txt', 'bar.txt'])252253If you don't like the ``--`` marker, you can set ignore_unknown_options to254True to avoid checking unknown options:255256.. click:example::257258    @click.command(context_settings={"ignore_unknown_options": True})259    @click.argument('files', nargs=-1, type=click.Path())260    def touch(files):261        """Print all FILES file names."""262        for filename in files:263            click.echo(filename)264265And from the command line:266267.. click:run::268269    invoke(touch, ['-foo.txt', 'bar.txt'])