Skip to content
Myr

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 file

Take 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 back
1Arguments
2=========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.40

Added support for nargs in other placesArmin Ronacherbefore adoption2e8354a

lines 41–42why, one step back
41The value is then passed as a tuple. Note that only one argument can be
42set to ``nargs=-1`` as this will eat up all arguments.

Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a

lines 43–48why, one step back
43
44Example:4546.. click:example::4748 @click.command()

Added support for nargs in other placesArmin Ronacherbefore adoption2e8354a

lines 49–53why, one step back
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))

Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a

lines 54–58why, one step back
54
55And what it looks like:5657.. click:run::58

Fixed a broken example in the docsArmin Ronacherbefore adoption20e8ffa

line 59why, one step back
59 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])

Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a

line 60why, one step back
60

Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7

lines 61–66why, one step back
61.. admonition:: Note on Non-Empty Variadic Arguments
6263 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 believe

Merge pull request #70 from julen/doc-fixesArmin Ronacherbefore adoption24b35b9

line 67why, one step back
67 scripts should gracefully degrade into becoming noops if a variadic

Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7

lines 68–71why, one step back
68 argument is empty. The reason for this is that very often scripts are
69 invoked with wildcard inputs from the command line and they should not70 error out if the wildcard is empty.71

Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a

lines 72–108why, one step back
72.. _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', '-'])108

Added lazy file openingArmin Ronacherbefore adoptionf270dd2

lines 109–127why, one step back
109File Opening Safety
110-------------------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.127

Documentation updates for file handlingArmin Ronacherbefore adoption72ae8a2

lines 128–135why, one step back
128Forcing on lazy mode is also very useful to avoid resource handling
129confusion. 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.135

Merge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0

line 136why, one step back
136Starting with click 2.0 it's also possible to open files in atomic mode by

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 137–138why, one step back
137passing ``atomic=True``. In atomic mode all writes go into a separate
138file in the same folder and upon completion the file will be moved over to

Merge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0

lines 139–140why, one step back
139the original location. This is useful if a file regularly read by other
140users is modified.

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

line 141why, one step back
141

Made tests pass on 3.xArmin Ronacherbefore adoption14c9b1a

lines 142–171why, one step back
142Environment Variables
143---------------------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 back
172
173Arguments 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'])