Break up arguments section (#2586)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents bed0377, 3241541 · Browse files · 5 files·+163 added−175 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+163 added−175 removed
- other:+163 added−175 removed
Provenance
- Commit
8e7bed0- Tree
057ceda- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
bed0377- Parent 2
3241541
5 files changed+163 added−175 removed
modified:docs/arguments.rst+63 added-171 removed
3 unmodified lines4 =========5 6 .. currentmodule:: click7 8-Arguments work similarly to :ref:`options <options>` but are positional.9-They also only support a subset of the features of options due to their10-syntactical nature. Click will also not attempt to document arguments for11-you and wants you to :ref:`document them manually <documenting-arguments>`12-in order to avoid ugly help pages.8+Arguments are:9 10+* Are positional in nature.11+* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12+* :ref:`Documented manually <documenting-arguments>`.13+14+Useful and often used kwargs are:15+16+* ``default``: Passes a default.17+* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.18+19 Basic Arguments20 ---------------21 17-The most basic option is a simple string argument of one value. If no18-type is provided, the type of the default value is used, and if no default19-value is provided, the type is assumed to be :data:`STRING`.22+A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.23 24 Example:25 26 .. click:example::27 28 @click.command()29 @click.argument('filename')27- def touch(filename):30+ def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)33 31-And what it looks like:34+And from the command line:35 36 .. click:run::37 38 invoke(touch, args=['foo.txt'])39 37-Variadic Arguments38-------------------40 40-The second most common version is variadic arguments where a specific (or41-unlimited) number of arguments is accepted. This can be controlled with42-the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number43-of arguments is accepted.41+An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.42 45-The value is then passed as a tuple. Note that only one argument can be46-set to ``nargs=-1``, as it will eat up all arguments.43+.. admonition:: Note on Required Arguments44 48-Example:45+ It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.46 47+Multiple Arguments48+-----------------------------------49+50+To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.51+52 .. click:example::53 54 @click.command()53- @click.argument('src', nargs=-1)54- @click.argument('dst', nargs=1)55- def copy(src, dst):55+ @click.argument('src', nargs=1)56+ @click.argument('dsts', nargs=-1)57+ def copy(src: str, dsts: tuple[str, ...]):58 """Move file SRC to DST."""57- for fn in src:58- click.echo(f"move {fn} to folder {dst}")59+ for destination in dsts:60+ click.echo(f"Copy {src} to folder {destination}")61 60-And what it looks like:62+And from the command line:63 64 .. click:run::65 64- invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])66+ invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])67 66-Note that this is not how you would write this application. The reason67-for this is that in this particular example the arguments are defined as68-strings. Filenames, however, are not strings! They might be on certain69-operating systems, but not necessarily on all. For better ways to write70-this, see the next sections.68+.. admonition:: Note on Handling Files69 72-.. admonition:: Note on Non-Empty Variadic Arguments70+ This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.71 74- If you come from ``argparse``, you might be missing support for setting75- ``nargs`` to ``+`` to indicate that at least one argument is required.72+Argument Escape Sequences73+---------------------------74 77- 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.75+If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.76 84-.. _file-args:77+Example usage:78 86-File Arguments87---------------88-89-Since all the examples have already worked with filenames, it makes sense90-to explain how to deal with files properly. Command line tools are more91-fun if they work with files the Unix way, which is to accept ``-`` as a92-special file that refers to stdin/stdout.93-94-Click supports this through the :class:`click.File` type which95-intelligently handles files for you. It also deals with Unicode and bytes96-correctly for all versions of Python so your script stays very portable.97-98-Example:99-79 .. click:example::80 81 @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)82+ @click.argument('files', nargs=-1, type=click.Path())83+ def touch(files):84+ """Print all FILES file names."""85+ for filename in files:86+ click.echo(filename)87 113-And what it does:88+And from the command line:89 90 .. click:run::91 117- with isolated_filesystem():118- invoke(inout, args=['-', 'hello.txt'], input=['hello'],119- terminate_input=True)120- invoke(inout, args=['hello.txt', '-'])92+ invoke(touch, ['--', '-foo.txt', 'bar.txt'])93 122-File Path Arguments123--------------------94+If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:95 125-In the previous example, the files were opened immediately. But what if126-we just want the filename? The naïve way is to use the default string127-argument type. The :class:`Path` type has several checks available which raise nice128-errors if they fail, such as existence. Filenames in these error messages are formatted129-with :func:`format_filename`, so any undecodable bytes will be printed nicely.130-131-Example:132-96 .. click:example::97 135- @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))98+ @click.command(context_settings={"ignore_unknown_options": True})99+ @click.argument('files', nargs=-1, type=click.Path())100+ def touch(files):101+ """Print all FILES file names."""102+ for filename in files:103+ click.echo(filename)104 141-And what it does:105+And from the command line:106 107 .. click:run::108 145- with isolated_filesystem():146- with open('hello.txt', 'w') as f:147- f.write('Hello World!\n')148- invoke(touch, args=['hello.txt'])109+ invoke(touch, ['-foo.txt', 'bar.txt'])149- println()150- invoke(touch, args=['missing.txt'])110 111 153-File Opening Safety154--------------------155-156-The :class:`FileType` type has one problem it needs to deal with, and that157-is 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/stdout159-and files opened for reading immediately. This will give the user direct160-feedback when a file cannot be opened, but it will only open files161-for writing the first time an IO operation is performed by automatically162-wrapping the file in a special wrapper.163-164-This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to165-the constructor. If the file is opened lazily, it will fail its first IO166-operation by raising an :exc:`FileError`.167-168-Since files opened for writing will typically immediately empty the file,169-the lazy mode should only be disabled if the developer is absolutely sure170-that this is intended behavior.171-172-Forcing lazy mode is also very useful to avoid resource handling173-confusion. If a file is opened in lazy mode, it will receive a174-``close_intelligently`` method that can help figure out if the file175-needs closing or not. This is not needed for parameters, but is176-necessary for manually prompting with the :func:`prompt` function as you177-do not know if a stream like stdout was opened (which was already open178-before) or a real file that needs closing.179-180-Starting with Click 2.0, it is also possible to open files in atomic mode by181-passing ``atomic=True``. In atomic mode, all writes go into a separate182-file in the same folder, and upon completion, the file will be moved over to183-the original location. This is useful if a file regularly read by other184-users is modified.185-186-112 .. _environment-variables:113 114 Environment Variables115 ---------------------116 192-Like options, arguments can also grab values from an environment variable.193-Unlike options, however, this is only supported for explicitly named194-environment variables.117+Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118 196-Example usage:119+Checking one environment variable:120 121 .. click:example::122 123 @click.command()6 unmodified lines130 131 .. click:run::132 133 with isolated_filesystem():134+ # Writing the file in the filesystem.135 with open('hello.txt', 'w') as f:136 f.write('Hello World!')137 invoke(echo, env={'SRC': 'hello.txt'})138 215-In that case, it can also be a list of different environment variables216-where the first one is picked.139 218-Generally, this feature is not recommended because it can cause the user219-a lot of confusion.140+Checking multiple environment variables:141 221-Option-Like Arguments222----------------------223-224-Sometimes, you want to process arguments that look like options. For225-instance, imagine you have a file named ``-foo.txt``. If you pass this as226-an argument in this manner, Click will treat it as an option.227-228-To solve this, Click does what any POSIX style command line script does,229-and that is to accept the string ``--`` as a separator for options and230-arguments. After the ``--`` marker, all further parameters are accepted as231-arguments.232-233-Example usage:234-142 .. click:example::143 144 @click.command()238- @click.argument('files', nargs=-1, type=click.Path())239- def touch(files):240- """Print all FILES file names."""241- for filename in files:242- click.echo(filename)145+ @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))146+ def echo(src):147+ """Print value of SRC environment variable."""148+ click.echo(src.read())149 150 And from the command line:151 152 .. click:run::153 248- invoke(touch, ['--', '-foo.txt', 'bar.txt'])249-250-If you don't like the ``--`` marker, you can set ignore_unknown_options to251-True to avoid checking unknown options:252-253-.. click:example::254-255- @click.command(context_settings={"ignore_unknown_options": True})256- @click.argument('files', nargs=-1, type=click.Path())257- def touch(files):258- """Print all FILES file names."""259- for filename in files:260- click.echo(filename)261-262-And from the command line:263-264-.. click:run::265-266- invoke(touch, ['-foo.txt', 'bar.txt'])154+ with isolated_filesystem():155+ # Writing the file in the filesystem.156+ with open('hello.txt', 'w') as f:157+ f.write('Hello World from second variable!')158+ invoke(echo, env={'SRC_2': 'hello.txt'})added:docs/handling-files.rst+90 added
1+.. _handling-files:2+3+Handling Files4+================5+6+.. currentmodule:: click7+8+Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.9+10+.. _file-args:11+12+File Arguments13+-----------------14+15+Click supports working with files with the :class:`File` type. Some notable features are:16+17+* Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities.18+* Deals with ``str`` and ``bytes`` correctly for all versions of Python.19+20+Example:21+22+.. click:example::23+24+ @click.command()25+ @click.argument('input', type=click.File('rb'))26+ @click.argument('output', type=click.File('wb'))27+ def inout(input, output):28+ """Copy contents of INPUT to OUTPUT."""29+ while True:30+ chunk = input.read(1024)31+ if not chunk:32+ break33+ output.write(chunk)34+35+And from the command line:36+37+.. click:run::38+39+ with isolated_filesystem():40+ invoke(inout, args=['-', 'hello.txt'], input=['hello'],41+ terminate_input=True)42+ invoke(inout, args=['hello.txt', '-'])43+44+File Path Arguments45+----------------------46+47+For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:48+49+* The ``exists`` argument will verify whether the path exists.50+* ``readable``, ``writable``, and ``executable`` can perform permission checks.51+* ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted.52+* Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely.53+54+See :class:`Path` for all features.55+56+Example:57+58+.. click:example::59+60+ @click.command()61+ @click.argument('filename', type=click.Path(exists=True))62+ def touch(filename):63+ """Print FILENAME if the file exists."""64+ click.echo(click.format_filename(filename))65+66+And from the command line:67+68+.. click:run::69+70+ with isolated_filesystem():71+ with open('hello.txt', 'w') as f:72+ f.write('Hello World!\n')73+ invoke(touch, args=['hello.txt'])74+ println()75+ invoke(touch, args=['missing.txt'])76+77+78+File Opening Behaviors79+-----------------------------80+81+The :class:`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special wrapper.82+83+File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:84+85+* A failure at first IO operation will happen by raising an :exc:`FileError`.86+* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).87+88+Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.89+90+It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.modified:docs/index.rst+1 added
73 unmodified lines74 options75 arguments76 commands77 prompts78+ handling-files79 documentation80 complex81 advanced82 testing27 unmodified linesmodified:docs/parameters.rst+2 added
51 unmodified lines52 .. click:run::53 54 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')55 56+.. _parameter-types:57+58 Parameter Types59 ---------------60 61 The supported parameter types are:78 unmodified linesmodified:src/click/types.py+7 added-4 removed
657 unmodified lines658 file lazily for reading, it is still opened temporarily for validation, but659 will not be held open until first IO. lazy is mainly useful when opening660 for writing to avoid creating the file until it is needed.661 662- Starting with Click 2.0, files can also be opened atomically in which663- case all writes go into a separate file in the same folder and upon664- completion the file will be moved over to the original location. This665- is useful if a file regularly read by other users is modified.662+ Files can also be opened atomically in which case all writes go into a663+ separate file in the same folder and upon completion the file will664+ be moved over to the original location. This is useful if a file665+ regularly read by other users is modified.666 667 See :ref:`file-args` for more information.668+669+ .. versionchanged:: 2.0670+ Added the ``atomic`` parameter.671 """672 673 name = "filename"674 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep419 unmodified lines