arguments.rst
This file
Path
docs/arguments.rst
199 lines · 6.2 KiB
Last changed by
Merge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0
History of this fileTake it
The walk stopped after 200 commits: lines older than 14c9b1a point at it.
Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
lines 1–40why, one step back1Arguments2=========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.40Added support for nargs in other placesArmin Ronacherbefore adoption2e8354a
lines 41–42why, one step back41The value is then passed as a tuple. Note that only one argument can be42set to ``nargs=-1`` as this will eat up all arguments.Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
lines 43–48why, one step back4344Example:4546.. click:example::4748 @click.command()Added support for nargs in other placesArmin Ronacherbefore adoption2e8354a
lines 49–53why, one step back49 @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))Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
lines 54–58why, one step back5455And what it looks like:5657.. click:run::58Fixed a broken example in the docsArmin Ronacherbefore adoption20e8ffa
line 59why, one step back59 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
line 60why, one step back60Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7
lines 61–66why, one step back61.. admonition:: Note on Non-Empty Variadic Arguments6263 If you come from ``argparse`` you might be missing support for setting64 ``nargs`` to ``+`` to indicate that at least one argument is required.6566 Support for this is very intentionally not included as we believeMerge pull request #70 from julen/doc-fixesArmin Ronacherbefore adoption24b35b9
line 67why, one step back67 scripts should gracefully degrade into becoming noops if a variadicAdded notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7
lines 68–71why, one step back68 argument is empty. The reason for this is that very often scripts are69 invoked with wildcard inputs from the command line and they should not70 error out if the wildcard is empty.71Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
lines 72–108why, one step back72.. _file-args:7374File Arguments75--------------7677Since all the examples have already worked with file names it makes sense78to explain how to deal with files properly. Command line tools are more79fun if they work with files the unix way which is to accept ``-`` as a80special file that refers to stdin/stdout.8182Click supports this through the :class:`click.File` type which83intelligently handles files for you. It also deals with unicode and bytes84correctly for all versions of Python so your script stays very portable.8586Example:8788.. click:example::8990 @click.command()91 @click.argument('input', type=click.File('rb'))92 @click.argument('output', type=click.File('wb'))93 def inout(input, output):94 while True:95 chunk = input.read(1024)96 if not chunk:97 break98 output.write(chunk)99100And what it does:101102.. click:run::103104 with isolated_filesystem():105 invoke(inout, args=['-', 'hello.txt'], input=['hello'],106 terminate_input=True)107 invoke(inout, args=['hello.txt', '-'])108Added lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 109–127why, one step back109File Opening Safety110-------------------111112The :class:`FileType` type has one problem it needs to deal with and that113is to decide when to open a file. The default behavior is to be114"intelligent" about it. What this means is that it will open stdin/stdout115and files opened for reading immediately. This will directly give the116user feedback when a file cannot be opened. But it will only open files117for writing the first time an IO operation is performed by wrapping the118file automatically in a special wrapper.119120This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to121the constructor. If the file is openened lazily it will fail on first IO122operation by raising an :exc:`FileError`.123124Since files opened for writing will typically immediatley empty the file,125the lazy mode should really only be disabled if the developer is 100% sure126that this is intended behavior.127Documentation updates for file handlingArmin Ronacherbefore adoption72ae8a2
lines 128–135why, one step back128Forcing on lazy mode is also very useful to avoid resource handling129confusion. If a file is opened in lazy mode it will get a130``close_intelligently`` method that can help you figuring out if the file131needs closing or not. This is not needed for parameters, but it is132necessary for manually prompting with the :func:`prompt` function as you133do not know if a stream like stdout was openend (which was already open134before) or a real file that needs closing.135Merge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0
line 136why, one step back136Starting with click 2.0 it's also possible to open files in atomic mode byImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 137–138why, one step back137passing ``atomic=True``. In atomic mode all writes go into a separate138file in the same folder and upon completion the file will be moved over toMerge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0
lines 139–140why, one step back139the original location. This is useful if a file regularly read by other140users is modified.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 141why, one step back141Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a
lines 142–171why, one step back142Environment Variables143---------------------144145Like options, arguments can also get values from an environment variable.146Unlike options however this is only supported for explicitly named147environment variables.148149Example usage:150151.. click:example::152153 @click.command()154 @click.argument('src', envvar='SRC', type=click.File('r'))155 def echo(src):156 click.echo(src.read())157158And from the command line:159160.. click:run::161162 with isolated_filesystem():163 with open('hello.txt', 'w') as f:164 f.write('Hello World!')165 invoke(echo, env={'SRC': 'hello.txt'})166167In that case it can also be a list of different environment variables168where the first one is picked.169170Generally this feature is not recommended because it can cause a lot of171confusion to the user.Mentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
lines 172–199why, one step back172173Arguments looking like Options174------------------------------175176Sometimes you want to process arguments that look like options. For177instance imagine you have a file named ``-foo.txt``. If you pass this as178such as an argument click will treat it as an option.179180To solve this, click does what any POSIX style command line script does181and that is to accept the string ``--`` as a separator for options and182arguments. After the ``--`` marker all further parameters are accepted as183arguments.184185Example usage:186187.. click:example::188189 @click.command()190 @click.argument('files', nargs=-1, type=click.Path())191 def touch(files):192 for filename in files:193 click.echo(filename)194195And from the command line:196197.. click:run::198199 invoke(touch, ['--', '-foo.txt', 'bar.txt'])