arguments.rst
This file
Path
docs/arguments.rst
242 lines · 7.6 KiB
Last changed by
Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
History of this fileTake it
The walk stopped after 200 commits: lines older than 09d219d point at it.
Added travis configArmin Ronacherbefore adoption09d219d
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.Added travis configArmin Ronacherbefore adoption09d219d
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))Added travis configArmin Ronacherbefore adoption09d219d
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'])Added travis configArmin Ronacherbefore adoption09d219d
line 60why, one step back60Added docs for path typeArmin Ronacherbefore adoptionc13d723
lines 61–66why, one step back61Note that this is not how you would write this application. The reason62for this is that in this particular example the arguments are defined as63strings. File names however are not strings! They might be (on certain64operating systems) but not necessarily on others. For better ways see the65next sections.66Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7
lines 67–71why, one step back67.. admonition:: Note on Non-Empty Variadic Arguments6869 If you come from ``argparse`` you might be missing support for setting70 ``nargs`` to ``+`` to indicate that at least one argument is required.71Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 72why, one step back72 This is supported by setting ``required=True``. However, this shouldsetting a default for arguments now implicitly makes it non requiredArmin Ronacherbefore adoption71da0b4
lines 73–74why, one step back73 not be used if you can avoid it as we believe scripts should gracefully74 degrade into becoming noops if a variadic argument is empty. TheMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 75why, one step back75 reason for this is that very often, scripts are invoked with wildcardsetting a default for arguments now implicitly makes it non requiredArmin Ronacherbefore adoption71da0b4
lines 76–77why, one step back76 inputs from the command line and they should not error out if the77 wildcard is empty.Added notes on missing "+" from argparseArmin Ronacherbefore adoption1ad7df7
line 78why, one step back78Added travis configArmin Ronacherbefore adoption09d219d
lines 79–83why, one step back79.. _file-args:8081File Arguments82--------------83Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 84why, one step back84Since all the examples have already worked with filenames, it makes senseAdded travis configArmin Ronacherbefore adoption09d219d
line 85why, one step back85to explain how to deal with files properly. Command line tools are moreMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 86why, one step back86fun if they work with files the Unix way which is to accept ``-`` as aAdded travis configArmin Ronacherbefore adoption09d219d
lines 87–89why, one step back87special file that refers to stdin/stdout.8889Click supports this through the :class:`click.File` type whichMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 90why, one step back90intelligently handles files for you. It also deals with Unicode and bytesAdded travis configArmin Ronacherbefore adoption09d219d
lines 91–114why, one step back91correctly for all versions of Python so your script stays very portable.9293Example:9495.. click:example::9697 @click.command()98 @click.argument('input', type=click.File('rb'))99 @click.argument('output', type=click.File('wb'))100 def inout(input, output):101 while True:102 chunk = input.read(1024)103 if not chunk:104 break105 output.write(chunk)106107And what it does:108109.. click:run::110111 with isolated_filesystem():112 invoke(inout, args=['-', 'hello.txt'], input=['hello'],113 terminate_input=True)114 invoke(inout, args=['hello.txt', '-'])Added docs for path typeArmin Ronacherbefore adoptionc13d723
lines 115–125why, one step back115116File Path Arguments117-------------------118119In the previous example the files were opened immediately. But what if120we just want the filename? The naive way is to use the default string121argument type. However remember that click is unicode based so the string122will be a unicode value always. Filenames unfortunately however can be123unicode or bytes depending on which operating system you're on. As such124the type is insufficient.125Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 126–127why, one step back126Instead, you should be using the :class:`Path` type which handles this127complexity for you. Not only will it return either bytes or UnicodeAdded docs for path typeArmin Ronacherbefore adoptionc13d723
lines 128–150why, one step back128depending on what makes more sense, but it will also be able to do some129basic checks for you such as existence checks.130131Example:132133.. click:example::134135 @click.command()136 @click.argument('f', type=click.Path(exists=True))137 def touch(f):138 click.echo(click.format_filename(f))139140And what it does:141142.. click:run::143144 with isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!\n')147 invoke(touch, args=['hello.txt'])148 println()149 invoke(touch, args=['missing.txt'])150Added travis configArmin Ronacherbefore adoption09d219d
line 151why, one step back151Added lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 152–158why, one step back152File Opening Safety153-------------------154155The :class:`FileType` type has one problem it needs to deal with and that156is to decide when to open a file. The default behavior is to be157"intelligent" about it. What this means is that it will open stdin/stdout158and files opened for reading immediately. This will directly give theMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 159why, one step back159user feedback when a file cannot be opened, but it will only open filesAdded lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 160–163why, one step back160for writing the first time an IO operation is performed by wrapping the161file automatically in a special wrapper.162163This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` toMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 164why, one step back164the constructor. If the file is opened lazily, it will fail on first IOAdded lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 165–166why, one step back165operation by raising an :exc:`FileError`.166Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 167–168why, one step back167Since files opened for writing will typically immediately empty the file,168the lazy mode should only be disabled if the developer is absolutely sureAdded lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 169–170why, one step back169that this is intended behavior.170Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 171–174why, one step back171Forcing lazy mode is also very useful to avoid resource handling172confusion. If a file is opened in lazy mode, it will receive a173``close_intelligently`` method that can help figure out if the file174needs closing or not. This is not needed for parameters, but isDocumentation updates for file handlingArmin Ronacherbefore adoption72ae8a2
line 175why, one step back175necessary for manually prompting with the :func:`prompt` function as youMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 176why, one step back176do not know if a stream like stdout was opened (which was already openDocumentation updates for file handlingArmin Ronacherbefore adoption72ae8a2
lines 177–178why, one step back177before) or a real file that needs closing.178Merge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0
line 179why, one step back179Starting with click 2.0 it's also possible to open files in atomic mode byMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 180why, one step back180passing ``atomic=True``. In atomic mode, all writes go into a separateImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 181why, one step back181file in the same folder and upon completion the file will be moved over toMerge pull request #93 from julen/doc-fixesArmin Ronacherbefore adoption82973d0
lines 182–183why, one step back182the original location. This is useful if a file regularly read by other183users is modified.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 184why, one step back184Added travis configArmin Ronacherbefore adoption09d219d
lines 185–188why, one step back185Environment Variables186---------------------187188Like options, arguments can also get values from an environment variable.Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 189why, one step back189Unlike options, however, this is only supported for explicitly namedAdded travis configArmin Ronacherbefore adoption09d219d
lines 190–209why, one step back190environment variables.191192Example usage:193194.. click:example::195196 @click.command()197 @click.argument('src', envvar='SRC', type=click.File('r'))198 def echo(src):199 click.echo(src.read())200201And from the command line:202203.. click:run::204205 with isolated_filesystem():206 with open('hello.txt', 'w') as f:207 f.write('Hello World!')208 invoke(echo, env={'SRC': 'hello.txt'})209Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 210why, one step back210In that case, it can also be a list of different environment variablesAdded travis configArmin Ronacherbefore adoption09d219d
lines 211–214why, one step back211where the first one is picked.212213Generally this feature is not recommended because it can cause a lot of214confusion to the user.Mentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
line 215why, one step back215Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 216why, one step back216Arguments-Like OptionsMentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
lines 217–219why, one step back217------------------------------218219Sometimes you want to process arguments that look like options. ForMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 220–221why, one step back220instance, imagine you have a file named ``-foo.txt``. If you pass this as221an argument in this manner, click will treat it as an option.Mentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
line 222why, one step back222Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 223why, one step back223To solve this, click does what any POSIX style command line script does,Mentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
line 224why, one step back224and that is to accept the string ``--`` as a separator for options andMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 225why, one step back225arguments. After the ``--`` marker, all further parameters are accepted asMentioned "--" in the docs.Armin Ronacherbefore adoption5f8c04f
lines 226–242why, one step back226arguments.227228Example usage:229230.. click:example::231232 @click.command()233 @click.argument('files', nargs=-1, type=click.Path())234 def touch(files):235 for filename in files:236 click.echo(filename)237238And from the command line:239240.. click:run::241242 invoke(touch, ['--', '-foo.txt', 'bar.txt'])