Skip to content
Myr

arguments.rst

This file

Path

docs/arguments.rst

242 lines · 7.6 KiB

Last changed by

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

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'])6061Note that this is not how you would write this application.  The reason62for this is that in this particular example the arguments are defined as63strings.  File names however are not strings!  They might be (on certain64operating systems) but not necessarily on others.  For better ways see the65next sections.6667.. admonition:: Note on Non-Empty Variadic Arguments6869   If you come from ``argparse`` you might be missing support for setting70   ``nargs`` to ``+`` to indicate that at least one argument is required.7172   This is supported by setting ``required=True``.  However, this should73   not be used if you can avoid it as we believe scripts should gracefully74   degrade into becoming noops if a variadic argument is empty.  The75   reason for this is that very often, scripts are invoked with wildcard76   inputs from the command line and they should not error out if the77   wildcard is empty.7879.. _file-args:8081File Arguments82--------------8384Since all the examples have already worked with filenames, it makes sense85to explain how to deal with files properly.  Command line tools are more86fun if they work with files the Unix way which is to accept ``-`` as a87special file that refers to stdin/stdout.8889Click supports this through the :class:`click.File` type which90intelligently handles files for you.  It also deals with Unicode and bytes91correctly for all versions of Python so your script stays very portable.9293Example:9495.. click:example::9697    @click.command()98    @click.argument('input', type=click.File('rb'))99    @click.argument('output', type=click.File('wb'))100    def inout(input, output):101        while True:102            chunk = input.read(1024)103            if not chunk:104                break105            output.write(chunk)106107And what it does:108109.. click:run::110111    with isolated_filesystem():112        invoke(inout, args=['-', 'hello.txt'], input=['hello'],113               terminate_input=True)114        invoke(inout, args=['hello.txt', '-'])115116File Path Arguments117-------------------118119In the previous example the files were opened immediately.  But what if120we just want the filename?  The naive way is to use the default string121argument type.  However remember that click is unicode based so the string122will be a unicode value always.  Filenames unfortunately however can be123unicode or bytes depending on which operating system you're on.  As such124the type is insufficient.125126Instead, you should be using the :class:`Path` type which handles this127complexity for you.  Not only will it return either bytes or Unicode128depending on what makes more sense, but it will also be able to do some129basic checks for you such as existence checks.130131Example:132133.. click:example::134135    @click.command()136    @click.argument('f', type=click.Path(exists=True))137    def touch(f):138        click.echo(click.format_filename(f))139140And what it does:141142.. click:run::143144    with isolated_filesystem():145        with open('hello.txt', 'w') as f:146            f.write('Hello World!\n')147        invoke(touch, args=['hello.txt'])148        println()149        invoke(touch, args=['missing.txt'])150151152File Opening Safety153-------------------154155The :class:`FileType` type has one problem it needs to deal with and that156is to decide when to open a file.  The default behavior is to be157"intelligent" about it.  What this means is that it will open stdin/stdout158and files opened for reading immediately.  This will directly give the159user feedback when a file cannot be opened, but it will only open files160for writing the first time an IO operation is performed by wrapping the161file automatically in a special wrapper.162163This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to164the constructor.  If the file is opened lazily, it will fail on first IO165operation by raising an :exc:`FileError`.166167Since files opened for writing will typically immediately empty the file,168the lazy mode should only be disabled if the developer is absolutely sure169that this is intended behavior.170171Forcing lazy mode is also very useful to avoid resource handling172confusion.  If a file is opened in lazy mode, it will receive a173``close_intelligently`` method that can help figure out if the file174needs closing or not.  This is not needed for parameters, but is175necessary for manually prompting with the :func:`prompt` function as you176do not know if a stream like stdout was opened (which was already open177before) or a real file that needs closing.178179Starting with click 2.0 it's also possible to open files in atomic mode by180passing ``atomic=True``.  In atomic mode, all writes go into a separate181file in the same folder and upon completion the file will be moved over to182the original location.  This is useful if a file regularly read by other183users is modified.184185Environment Variables186---------------------187188Like options, arguments can also get values from an environment variable.189Unlike options, however, this is only supported for explicitly named190environment variables.191192Example usage:193194.. click:example::195196    @click.command()197    @click.argument('src', envvar='SRC', type=click.File('r'))198    def echo(src):199        click.echo(src.read())200201And from the command line:202203.. click:run::204205    with isolated_filesystem():206        with open('hello.txt', 'w') as f:207            f.write('Hello World!')208        invoke(echo, env={'SRC': 'hello.txt'})209210In that case, it can also be a list of different environment variables211where the first one is picked.212213Generally this feature is not recommended because it can cause a lot of214confusion to the user.215216Arguments-Like Options217------------------------------218219Sometimes you want to process arguments that look like options.  For220instance, imagine you have a file named ``-foo.txt``.  If you pass this as221an argument in this manner, click will treat it as an option.222223To solve this, click does what any POSIX style command line script does,224and that is to accept the string ``--`` as a separator for options and225arguments.  After the ``--`` marker, all further parameters are accepted as226arguments.227228Example usage:229230.. click:example::231232    @click.command()233    @click.argument('files', nargs=-1, type=click.Path())234    def touch(files):235        for filename in files:236            click.echo(filename)237238And from the command line:239240.. click:run::241242    invoke(touch, ['--', '-foo.txt', 'bar.txt'])