Skip to content
Myr

Rough out changes to arguments section.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by unknown · committed by unknown · parent ce6e066 · Browse files · 5 files+170 added−218 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+170 added−218 removed

  • other:+170 added−218 removed

5 files+170 added−218 removed

modified:docs/arguments.rst+48 added-177 removed
3 unmodified lines
4=========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.8Arguments : 910* are positional in nature 11* are very much like a limited version of :ref:`options <options>`12* but also can take an arbitrary number of inputs 13* must be :ref:`documented manually <documenting-arguments>` 1415Useful and often used kwargs are: 1617* ``default`` : passes a default18* ``nargs`` : Sets the number of arguments. Set to -1 to take an arbitrary number. 1914Basic Arguments20Basic Argument21---------------2217The 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`.23A minimal :class:`click.Argument` takes the name of function argument. If you just pass it this, it assumes 1 argument, required, no default and string type.2425Example:2627.. click:example::
9 unmodified lines
37.. click:run::3839 invoke(touch, args=['foo.txt'])4037Variadic Arguments38------------------4140The 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.42Not sure if should include : If no type is provided, the type of the default value is used, and if no default value is provided, the type is assumed to be STRING. 4345The value is then passed as a tuple. Note that only one argument can be46set to ``nargs=-1``, as it will eat up all arguments.44Multiple Arguments45-----------------------------------4648Example:47To 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.4849.. click:example::5051 @click.command()53 @click.argument('src', nargs=-1)54 @click.argument('dst', nargs=1)55 def copy(src, dst):52 @click.argument('src', nargs=1)53 @click.argument('dsts', nargs=-1)54 def copy(src, dsts):55 """Move file SRC to DST."""57 for fn in src:58 click.echo(f"move {fn} to folder {dst}")56 for destination in dsts:57 click.echo(f"Copy {src} to folder {destination}")5859And what it looks like:6061.. click:run::6264 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])63 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])6466Note 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.65Note this example is not how you would handle files and files paths, since it passes them in as strings. For more see :ref:`handling-files`.6672.. admonition:: Note on Non-Empty Variadic Arguments67.. admonition:: Note on Required Arguments6874 If you come from ``argparse``, you might be missing support for setting75 ``nargs`` to ``+`` to indicate that at least one argument is required.69 It is not recommended, but you may make at least one argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming noops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.7077 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.7184.. _file-args:7286File Arguments87--------------73Argument Escape Sequences74---------------------------7589Since 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.76If you want to process arguments that look like options, like a file named ``-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. 7794Click 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.78Example usage:7998Example:9980.. click:example::8182 @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)83 @click.argument('files', nargs=-1, type=click.Path())84 def touch(files):85 """Print all FILES file names."""86 for filename in files:87 click.echo(filename)88113And what it does:89And from the command line:9091.. click:run::92117 with isolated_filesystem():118 invoke(inout, args=['-', 'hello.txt'], input=['hello'],119 terminate_input=True)120 invoke(inout, args=['hello.txt', '-'])93 invoke(touch, ['--', '-foo.txt', 'bar.txt'])94122File Path Arguments123-------------------95If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:96125In the previous example, the files were opened immediately. But what if126we just want the filename? The naïve way is to use the default string127argument type. The :class:`Path` type has several checks available which raise nice128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.130131Example:13297.. click:example::98135 @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))99 @click.command(context_settings={"ignore_unknown_options": True})100 @click.argument('files', nargs=-1, type=click.Path())101 def touch(files):102 """Print all FILES file names."""103 for filename in files:104 click.echo(filename)105141And what it does:106And from the command line:107108.. click:run::109145 with isolated_filesystem():146 with open('hello.txt', 'w') as f:147 f.write('Hello World!\n')148 invoke(touch, args=['hello.txt'])110 invoke(touch, ['-foo.txt', 'bar.txt'])149 println()150 invoke(touch, args=['missing.txt'])111152153File 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.185112Environment Variables113---------------------114189Like options, arguments can also grab values from an environment variable.190Unlike options, however, this is only supported for explicitly named191environment variables.115This feature is not recommended since it be confusing to users. Arguments can only pull environment variables from ? explicitly named environment variables. In that case, it can also be a list of different environment variables where the first one is picked. ?116117Example usage:118119.. click:example::
10 unmodified lines
130131 with isolated_filesystem():132 with open('hello.txt', 'w') as f:133 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'])134 invoke(echo, env={'SRC': 'hello.txt'})
added:docs/handling_files.rst+110 added
1.. _handling-files:23Handling Files 4================56.. currentmodule:: click78File and files paths are often passed in as arguments.910.. _file-args:1112File Arguments13--------------1415Since all the examples have already worked with filenames, it makes sense16to explain how to deal with files properly. Command line tools are more17fun if they work with files the Unix way, which is to accept ``-`` as a18special file that refers to stdin/stdout.1920Click supports this through the :class:`click.File` type which21intelligently handles files for you. It also deals with Unicode and bytes22correctly for all versions of Python so your script stays very portable.2324Example:2526.. click:example::2728 @click.command()29 @click.argument('input', type=click.File('rb'))30 @click.argument('output', type=click.File('wb'))31 def inout(input, output):32 """Copy contents of INPUT to OUTPUT."""33 while True:34 chunk = input.read(1024)35 if not chunk:36 break37 output.write(chunk)3839And what it does:4041.. click:run::4243 with isolated_filesystem():44 invoke(inout, args=['-', 'hello.txt'], input=['hello'],45 terminate_input=True)46 invoke(inout, args=['hello.txt', '-'])4748File Path Arguments49-------------------5051In the previous example, the files were opened immediately. But what if52we just want the filename? The naïve way is to use the default string53argument type. The :class:`Path` type has several checks available which raise nice54errors if they fail, such as existence. Filenames in these error messages are formatted55with :func:`format_filename`, so any undecodable bytes will be printed nicely.5657Example:5859.. click:example::6061 @click.command()62 @click.argument('filename', type=click.Path(exists=True))63 def touch(filename):64 """Print FILENAME if the file exists."""65 click.echo(click.format_filename(filename))6667And what it does:6869.. click:run::7071 with isolated_filesystem():72 with open('hello.txt', 'w') as f:73 f.write('Hello World!\n')74 invoke(touch, args=['hello.txt'])75 println()76 invoke(touch, args=['missing.txt'])777879File Opening Safety80-------------------8182The :class:`FileType` type has one problem it needs to deal with, and that83is to decide when to open a file. The default behavior is to be84"intelligent" about it. What this means is that it will open stdin/stdout85and files opened for reading immediately. This will give the user direct86feedback when a file cannot be opened, but it will only open files87for writing the first time an IO operation is performed by automatically88wrapping the file in a special wrapper.8990This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to91the constructor. If the file is opened lazily, it will fail its first IO92operation by raising an :exc:`FileError`.9394Since files opened for writing will typically immediately empty the file,95the lazy mode should only be disabled if the developer is absolutely sure96that this is intended behavior.9798Forcing lazy mode is also very useful to avoid resource handling99confusion. If a file is opened in lazy mode, it will receive a100``close_intelligently`` method that can help figure out if the file101needs closing or not. This is not needed for parameters, but is102necessary for manually prompting with the :func:`prompt` function as you103do not know if a stream like stdout was opened (which was already open104before) or a real file that needs closing.105106Starting with Click 2.0, it is also possible to open files in atomic mode by107passing ``atomic=True``. In atomic mode, all writes go into a separate108file in the same folder, and upon completion, the file will be moved over to109the original location. This is useful if a file regularly read by other110users is modified.
modified:docs/index.rst+1 added
70 unmodified lines
71 setuptools72 parameters73 options74 arguments75 handling_files76 commands77 prompts78 documentation79 complex
29 unmodified lines
modified:.pre-commit-config.yaml+3 added-3 removed
modified:CHANGES.rst+8 added-38 removed
1.. currentmodule:: click23Version 8.1.63Version 8.2.04-------------56Released 2023-07-186Unreleased78- Fix an issue with type hints for ``@click.group()``. :issue:`2558`8- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.9 :pr:`326`10- Use ``flit_core`` instead of ``setuptools`` as build backend.111211Version 8.1.512-------------1314Released 2023-07-131516- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and17 other decorators. Introduce typing tests. :issue:`2558`181913Version 8.1.414-------------1523Released 2023-07-0616Unreleased1718- Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for26 parameter hints. :issue:`2255`19 parameter hints. :issue:`2255`20- Improve type hinting for decorators and give all generic types parameters.21 :issue:`2398`29- Fix return value and type signature of `shell_completion.add_completion_class`30 function. :pr:`2421`31- Bash version detection doesn't fail on Windows. :issue:`2461`32- Completion works if there is a dot (``.``) in the program name. :issue:`2166`33- Improve type annotations for pyright type checker. :issue:`2268`34- Improve responsiveness of ``click.clear()``. :issue:`2284`35- Improve command name detection when using Shiv or PEX. :issue:`2332`36- Avoid showing empty lines if command help text is empty. :issue:`2368`37- ZSH completion script works when loaded from ``fpath``. :issue:`2344`.38- ``EOFError`` and ``KeyboardInterrupt`` tracebacks are not suppressed when39 ``standalone_mode`` is disabled. :issue:`2380`40- ``@group.command`` does not fail if the group was created with a custom41 ``command_class``. :issue:`2416`42- ``multiple=True`` is allowed for flag options again and does not require43 setting ``default=()``. :issue:`2246, 2292, 2295`44- Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the45 ``cls`` parameter is used. :issue:`2294`46- Don't fail when writing filenames to streams with strict errors. Replace invalid47 bytes with the replacement character (``�``). :issue:`2395`48- Remove unnecessary attempt to detect MSYS2 environment. :issue:`2355`49- Remove outdated and unnecessary detection of App Engine environment. :pr:`2554`50- ``echo()`` does not fail when no streams are attached, such as with ``pythonw`` on51 Windows. :issue:`2415`52- Argument with ``expose_value=False`` do not cause completion to fail. :issue:`2336`22- Fix return value and type signature of `shell_completion.add_completion_class` function. :pr:`2421`232425Version 8.1.326-------------
1040 unmodified lines