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
The walk stopped after 200 commits: lines older than 5cae326 point at it.
Merge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoption4ee540d
lines 1–2why, one step back1.. _arguments:2Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 3–7why, one step back3Arguments4=========56.. currentmodule:: click7Merge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoption4ee540d
lines 8–12why, one step back8Arguments 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.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 13–17why, one step back1314Basic Arguments15---------------1617The most basic option is a simple string argument of one value. If noDocumentation fixesKevin Yapbefore adoption67523af
lines 18–19why, one step back18type is provided, the type of the default value is used, and if no default19value is provided, the type is assumed to be :data:`STRING`.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 20–40why, one step back2021Example: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 withDocumentation fixesKevin Yapbefore adoption67523af
line 41why, one step back41the ``nargs`` parameter. If it is set to ``-1``, then an unlimited numberMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 42–44why, one step back42of arguments is accepted.4344The value is then passed as a tuple. Note that only one argument can beDocumentation fixesKevin Yapbefore adoption67523af
line 45why, one step back45set to ``nargs=-1``, as it will eat up all arguments.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 46–65why, one step back4647Example: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 asDocumentation fixesKevin Yapbefore adoption67523af
lines 66–68why, one step back66strings. 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.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 69–71why, one step back6970.. admonition:: Note on Non-Empty Variadic Arguments71Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 72why, one step back72 If you come from ``argparse``, you might be missing support for settingMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 73–88why, one step back73 ``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 moreDocumentation fixesKevin Yapbefore adoption67523af
line 89why, one step back89fun if they work with files the Unix way, which is to accept ``-`` as aMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 90–121why, one step back90special 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-------------------121Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 122–123why, one step back122In the previous example, the files were opened immediately. But what if123we just want the filename? The naïve way is to use the default stringMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 124why, one step back124argument type. However, remember that Click is Unicode-based, so the stringDocumentation fixesKevin Yapbefore adoption67523af
lines 125–127why, one step back125will always be a Unicode value. Unfortunately, filenames can be Unicode or126bytes depending on which operating system is being used. As such, the type127is insufficient.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 128why, one step back128Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 129–130why, one step back129Instead, you should be using the :class:`Path` type, which automatically130handles this ambiguity. Not only will it return either bytes or UnicodeMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 131–157why, one step back131depending 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-------------------157Documentation fixesKevin Yapbefore adoption67523af
line 158why, one step back158The :class:`FileType` type has one problem it needs to deal with, and thatMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 159–160why, one step back159is 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/stdoutDocumentation fixesKevin Yapbefore adoption67523af
lines 161–164why, one step back161and 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.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 165–166why, one step back165166This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` toDocumentation fixesKevin Yapbefore adoption67523af
line 167why, one step back167the constructor. If the file is opened lazily, it will fail its first IOMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 168–181why, one step back168operation 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.181Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 182why, one step back182Starting with Click 2.0, it is also possible to open files in atomic mode byMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 183why, one step back183passing ``atomic=True``. In atomic mode, all writes go into a separateDocumentation fixesKevin Yapbefore adoption67523af
line 184why, one step back184file in the same folder, and upon completion, the file will be moved over toMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 185–190why, one step back185the original location. This is useful if a file regularly read by other186users is modified.187188Environment Variables189---------------------190Documentation fixesKevin Yapbefore adoption67523af
line 191why, one step back191Like options, arguments can also grab values from an environment variable.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 192–215why, one step back192Unlike 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.215Documentation fixesKevin Yapbefore adoption67523af
lines 216–217why, one step back216Generally, this feature is not recommended because it can cause the user217a lot of confusion.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 218why, one step back218Merge pull request #219 from ryanhiebert/option-like-argumentsArmin Ronacherbefore adoption308cc08
line 219why, one step back219Option-Like ArgumentsMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 220why, one step back220---------------------Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 221why, one step back221Documentation fixesKevin Yapbefore adoption67523af
line 222why, one step back222Sometimes, you want to process arguments that look like options. ForMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 223why, one step back223instance, imagine you have a file named ``-foo.txt``. If you pass this asMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 224why, one step back224an argument in this manner, Click will treat it as an option.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 225why, one step back225Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 226why, one step back226To solve this, Click does what any POSIX style command line script does,Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 227–245why, one step back227and 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'])