Skip to content
Myr

arguments.rst

This file

Path

docs/arguments.rst

263 lines · 8.2 KiB

Last changed by

Merge branch '8.1.x'David Lordbefore adoptiond9af5cf

History of this file

Take it

The walk stopped after 200 commits: lines older than 0827847 point at it.

Merge pull request #1768 from pallets/dependabot/pip/sphinx-tabs-2.0.0dependabot-preview[bot]before adoption0827847

lines 1–126why, one step back
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 string

Merge branch '8.1.x'David Lordbefore adoptiond9af5cf

lines 127–129why, one step back
127argument type. The :class:`Path` type has several checks available which raise nice
128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.

Merge pull request #1768 from pallets/dependabot/pip/sphinx-tabs-2.0.0dependabot-preview[bot]before adoption0827847

lines 130–263why, one step back
130
131Example:132133.. click:example::134135 @click.command()136 @click.argument('filename', type=click.Path(exists=True))137 def touch(filename):138 """Print FILENAME if the file exists."""139 click.echo(click.format_filename(filename))140141And what it does:142143.. click:run::144145 with isolated_filesystem():146 with open('hello.txt', 'w') as f:147 f.write('Hello World!\n')148 invoke(touch, args=['hello.txt'])149 println()150 invoke(touch, args=['missing.txt'])151152153File Opening Safety154-------------------155156The :class:`FileType` type has one problem it needs to deal with, and that157is to decide when to open a file. The default behavior is to be158"intelligent" about it. What this means is that it will open stdin/stdout159and files opened for reading immediately. This will give the user direct160feedback when a file cannot be opened, but it will only open files161for writing the first time an IO operation is performed by automatically162wrapping the file in a special wrapper.163164This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to165the constructor. If the file is opened lazily, it will fail its first IO166operation by raising an :exc:`FileError`.167168Since files opened for writing will typically immediately empty the file,169the lazy mode should only be disabled if the developer is absolutely sure170that this is intended behavior.171172Forcing lazy mode is also very useful to avoid resource handling173confusion. If a file is opened in lazy mode, it will receive a174``close_intelligently`` method that can help figure out if the file175needs closing or not. This is not needed for parameters, but is176necessary for manually prompting with the :func:`prompt` function as you177do not know if a stream like stdout was opened (which was already open178before) or a real file that needs closing.179180Starting with Click 2.0, it is also possible to open files in atomic mode by181passing ``atomic=True``. In atomic mode, all writes go into a separate182file in the same folder, and upon completion, the file will be moved over to183the original location. This is useful if a file regularly read by other184users is modified.185186Environment Variables187---------------------188189Like options, arguments can also grab values from an environment variable.190Unlike options, however, this is only supported for explicitly named191environment variables.192193Example usage:194195.. click:example::196197 @click.command()198 @click.argument('src', envvar='SRC', type=click.File('r'))199 def echo(src):200 """Print value of SRC environment variable."""201 click.echo(src.read())202203And from the command line:204205.. click:run::206207 with isolated_filesystem():208 with open('hello.txt', 'w') as f:209 f.write('Hello World!')210 invoke(echo, env={'SRC': 'hello.txt'})211212In that case, it can also be a list of different environment variables213where the first one is picked.214215Generally, this feature is not recommended because it can cause the user216a lot of confusion.217218Option-Like Arguments219---------------------220221Sometimes, you want to process arguments that look like options. For222instance, imagine you have a file named ``-foo.txt``. If you pass this as223an argument in this manner, Click will treat it as an option.224225To solve this, Click does what any POSIX style command line script does,226and that is to accept the string ``--`` as a separator for options and227arguments. After the ``--`` marker, all further parameters are accepted as228arguments.229230Example usage:231232.. click:example::233234 @click.command()235 @click.argument('files', nargs=-1, type=click.Path())236 def touch(files):237 """Print all FILES file names."""238 for filename in files:239 click.echo(filename)240241And from the command line:242243.. click:run::244245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])246247If you don't like the ``--`` marker, you can set ignore_unknown_options to248True to avoid checking unknown options:249250.. click:example::251252 @click.command(context_settings={"ignore_unknown_options": True})253 @click.argument('files', nargs=-1, type=click.Path())254 def touch(files):255 """Print all FILES file names."""256 for filename in files:257 click.echo(filename)258259And from the command line:260261.. click:run::262263 invoke(touch, ['-foo.txt', 'bar.txt'])