arguments.rst
This file
Path
docs/arguments.rst
245 lines · 7.7 KiB
Last changed by
Merge pull request #219 from ryanhiebert/option-like-argumentsArmin Ronacherbefore adoption308cc08
History of this fileTake 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 document them manually in order to avoid ugly help12pages.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 click.echo(filename)2930And what it looks like:3132.. click:run::3334 invoke(touch, args=['foo.txt'])3536Variadic Arguments37------------------3839The second most common version is variadic arguments where a specific (or40unlimited) number of arguments is accepted. This can be controlled with41the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number42of arguments is accepted.4344The value is then passed as a tuple. Note that only one argument can be45set to ``nargs=-1``, as it will eat up all arguments.4647Example:4849.. click:example::5051 @click.command()52 @click.argument('src', nargs=-1)53 @click.argument('dst', nargs=1)54 def copy(src, dst):55 for fn in src:56 click.echo('move %s to folder %s' % (fn, dst))5758And what it looks like:5960.. click:run::6162 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])6364Note that this is not how you would write this application. The reason65for this is that in this particular example the arguments are defined as66strings. Filenames, however, are not strings! They might be on certain67operating systems, but not necessarily on all. For better ways to write68this, see the next sections.6970.. admonition:: Note on Non-Empty Variadic Arguments7172 If you come from ``argparse``, you might be missing support for setting73 ``nargs`` to ``+`` to indicate that at least one argument is required.7475 This is supported by setting ``required=True``. However, this should76 not be used if you can avoid it as we believe scripts should gracefully77 degrade into becoming noops if a variadic argument is empty. The78 reason for this is that very often, scripts are invoked with wildcard79 inputs from the command line and they should not error out if the80 wildcard is empty.8182.. _file-args:8384File Arguments85--------------8687Since all the examples have already worked with filenames, it makes sense88to explain how to deal with files properly. Command line tools are more89fun if they work with files the Unix way, which is to accept ``-`` as a90special file that refers to stdin/stdout.9192Click supports this through the :class:`click.File` type which93intelligently handles files for you. It also deals with Unicode and bytes94correctly for all versions of Python so your script stays very portable.9596Example:9798.. click:example::99100 @click.command()101 @click.argument('input', type=click.File('rb'))102 @click.argument('output', type=click.File('wb'))103 def inout(input, output):104 while True:105 chunk = input.read(1024)106 if not chunk:107 break108 output.write(chunk)109110And what it does:111112.. click:run::113114 with isolated_filesystem():115 invoke(inout, args=['-', 'hello.txt'], input=['hello'],116 terminate_input=True)117 invoke(inout, args=['hello.txt', '-'])118119File Path Arguments120-------------------121122In the previous example, the files were opened immediately. But what if123we just want the filename? The naïve way is to use the default string124argument type. However, remember that Click is Unicode-based, so the string125will always be a Unicode value. Unfortunately, filenames can be Unicode or126bytes depending on which operating system is being used. As such, the type127is insufficient.128129Instead, you should be using the :class:`Path` type, which automatically130handles this ambiguity. Not only will it return either bytes or Unicode131depending on what makes more sense, but it will also be able to do some132basic checks for you such as existence checks.133134Example:135136.. click:example::137138 @click.command()139 @click.argument('f', type=click.Path(exists=True))140 def touch(f):141 click.echo(click.format_filename(f))142143And what it does:144145.. click:run::146147 with isolated_filesystem():148 with open('hello.txt', 'w') as f:149 f.write('Hello World!\n')150 invoke(touch, args=['hello.txt'])151 println()152 invoke(touch, args=['missing.txt'])153154155File Opening Safety156-------------------157158The :class:`FileType` type has one problem it needs to deal with, and that159is to decide when to open a file. The default behavior is to be160"intelligent" about it. What this means is that it will open stdin/stdout161and files opened for reading immediately. This will give the user direct162feedback when a file cannot be opened, but it will only open files163for writing the first time an IO operation is performed by automatically164wrapping the file in a special wrapper.165166This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to167the constructor. If the file is opened lazily, it will fail its first IO168operation by raising an :exc:`FileError`.169170Since files opened for writing will typically immediately empty the file,171the lazy mode should only be disabled if the developer is absolutely sure172that this is intended behavior.173174Forcing lazy mode is also very useful to avoid resource handling175confusion. If a file is opened in lazy mode, it will receive a176``close_intelligently`` method that can help figure out if the file177needs closing or not. This is not needed for parameters, but is178necessary for manually prompting with the :func:`prompt` function as you179do not know if a stream like stdout was opened (which was already open180before) or a real file that needs closing.181182Starting with Click 2.0, it is also possible to open files in atomic mode by183passing ``atomic=True``. In atomic mode, all writes go into a separate184file in the same folder, and upon completion, the file will be moved over to185the original location. This is useful if a file regularly read by other186users is modified.187188Environment Variables189---------------------190191Like options, arguments can also grab values from an environment variable.192Unlike options, however, this is only supported for explicitly named193environment variables.194195Example usage:196197.. click:example::198199 @click.command()200 @click.argument('src', envvar='SRC', type=click.File('r'))201 def echo(src):202 click.echo(src.read())203204And from the command line:205206.. click:run::207208 with isolated_filesystem():209 with open('hello.txt', 'w') as f:210 f.write('Hello World!')211 invoke(echo, env={'SRC': 'hello.txt'})212213In that case, it can also be a list of different environment variables214where the first one is picked.215216Generally, this feature is not recommended because it can cause the user217a lot of confusion.218219Option-Like Arguments220---------------------221222Sometimes, you want to process arguments that look like options. For223instance, imagine you have a file named ``-foo.txt``. If you pass this as224an argument in this manner, Click will treat it as an option.225226To solve this, Click does what any POSIX style command line script does,227and that is to accept the string ``--`` as a separator for options and228arguments. After the ``--`` marker, all further parameters are accepted as229arguments.230231Example usage:232233.. click:example::234235 @click.command()236 @click.argument('files', nargs=-1, type=click.Path())237 def touch(files):238 for filename in files:239 click.echo(filename)240241And from the command line:242243.. click:run::244245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])