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
Provenance
- Commit
30e907c- Tree
ffc6695- Author
unknown <edward.g2013@gmail.com>- Committer
unknown <edward.g2013@gmail.com>- Parent
ce6e066
5 files changed+170 added−218 removed
modified:docs/arguments.rst+48 added-177 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 : 9 10+* 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>` 14+15+Useful and often used kwargs are: 16+17+* ``default`` : passes a default18+* ``nargs`` : Sets the number of arguments. Set to -1 to take an arbitrary number. 19+14-Basic Arguments20+Basic Argument21 ---------------22 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`.23+A 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.24 25 Example:26 27 .. click:example::9 unmodified lines37 .. click:run::38 39 invoke(touch, args=['foo.txt'])40 37-Variadic Arguments38-------------------41 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.42+Not 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. 43 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.44+Multiple Arguments45+-----------------------------------46 48-Example:47+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.48 49 .. click:example::50 51 @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}")58 59 And what it looks like:60 61 .. click:run::62 64- invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])63+ invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])64 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.65+Note 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`.66 72-.. admonition:: Note on Non-Empty Variadic Arguments67+.. admonition:: Note on Required Arguments68 74- 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.70 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.71 84-.. _file-args:72 86-File Arguments87---------------73+Argument Escape Sequences74+---------------------------75 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.76+If 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. 77 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.78+Example usage:79 98-Example:99-80 .. click:example::81 82 @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)88 113-And what it does:89+And from the command line:90 91 .. click:run::92 117- 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'])94 122-File Path Arguments123--------------------95+If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:96 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-97 .. click:example::98 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))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)105 141-And what it does:106+And from the command line:107 108 .. click:run::109 145- 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'])111 152-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-112 Environment Variables113 ---------------------114 189-Like options, arguments can also grab values from an environment variable.190-Unlike options, however, this is only supported for explicitly named191-environment variables.115+This 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. ?116 117 Example usage:118 119 .. click:example::10 unmodified lines130 131 with isolated_filesystem():132 with open('hello.txt', 'w') as f:133 f.write('Hello World!')210- invoke(echo, env={'SRC': 'hello.txt'})211-212-In that case, it can also be a list of different environment variables213-where the first one is picked.214-215-Generally, this feature is not recommended because it can cause the user216-a lot of confusion.217-218-Option-Like Arguments219----------------------220-221-Sometimes, you want to process arguments that look like options. For222-instance, imagine you have a file named ``-foo.txt``. If you pass this as223-an argument in this manner, Click will treat it as an option.224-225-To solve this, Click does what any POSIX style command line script does,226-and that is to accept the string ``--`` as a separator for options and227-arguments. After the ``--`` marker, all further parameters are accepted as228-arguments.229-230-Example usage:231-232-.. click:example::233-234- @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)240-241-And from the command line:242-243-.. click:run::244-245- invoke(touch, ['--', '-foo.txt', 'bar.txt'])246-247-If you don't like the ``--`` marker, you can set ignore_unknown_options to248-True to avoid checking unknown options:249-250-.. click:example::251-252- @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)258-259-And from the command line:260-261-.. click:run::262-263- invoke(touch, ['-foo.txt', 'bar.txt'])134+ invoke(echo, env={'SRC': 'hello.txt'})added:docs/handling_files.rst+110 added
1+.. _handling-files:2+3+Handling Files 4+================5+6+.. currentmodule:: click7+8+File and files paths are often passed in as arguments.9+10+.. _file-args:11+12+File Arguments13+--------------14+15+Since all the examples have already worked with filenames, it makes sense16+to explain how to deal with files properly. Command line tools are more17+fun if they work with files the Unix way, which is to accept ``-`` as a18+special file that refers to stdin/stdout.19+20+Click supports this through the :class:`click.File` type which21+intelligently handles files for you. It also deals with Unicode and bytes22+correctly for all versions of Python so your script stays very portable.23+24+Example:25+26+.. click:example::27+28+ @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)38+39+And what it does:40+41+.. click:run::42+43+ with isolated_filesystem():44+ invoke(inout, args=['-', 'hello.txt'], input=['hello'],45+ terminate_input=True)46+ invoke(inout, args=['hello.txt', '-'])47+48+File Path Arguments49+-------------------50+51+In the previous example, the files were opened immediately. But what if52+we just want the filename? The naïve way is to use the default string53+argument type. The :class:`Path` type has several checks available which raise nice54+errors if they fail, such as existence. Filenames in these error messages are formatted55+with :func:`format_filename`, so any undecodable bytes will be printed nicely.56+57+Example:58+59+.. click:example::60+61+ @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))66+67+And what it does:68+69+.. click:run::70+71+ 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'])77+78+79+File Opening Safety80+-------------------81+82+The :class:`FileType` type has one problem it needs to deal with, and that83+is 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/stdout85+and files opened for reading immediately. This will give the user direct86+feedback when a file cannot be opened, but it will only open files87+for writing the first time an IO operation is performed by automatically88+wrapping the file in a special wrapper.89+90+This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to91+the constructor. If the file is opened lazily, it will fail its first IO92+operation by raising an :exc:`FileError`.93+94+Since files opened for writing will typically immediately empty the file,95+the lazy mode should only be disabled if the developer is absolutely sure96+that this is intended behavior.97+98+Forcing lazy mode is also very useful to avoid resource handling99+confusion. If a file is opened in lazy mode, it will receive a100+``close_intelligently`` method that can help figure out if the file101+needs closing or not. This is not needed for parameters, but is102+necessary for manually prompting with the :func:`prompt` function as you103+do not know if a stream like stdout was opened (which was already open104+before) or a real file that needs closing.105+106+Starting with Click 2.0, it is also possible to open files in atomic mode by107+passing ``atomic=True``. In atomic mode, all writes go into a separate108+file in the same folder, and upon completion, the file will be moved over to109+the original location. This is useful if a file regularly read by other110+users is modified.modified:docs/index.rst+1 added
70 unmodified lines71 setuptools72 parameters73 options74 arguments75+ handling_files76 commands77 prompts78 documentation79 complex29 unmodified linesmodified:.pre-commit-config.yaml+3 added-3 removed
123456678910111213141516161718192020212223247 unmodified linesci: autoupdate_branch: "8.1.x" autoupdate_schedule: monthlyrepos: - repo: https://github.com/asottile/pyupgrade rev: v3.10.1 rev: v3.7.0 hooks: - id: pyupgrade args: ["--py37-plus"] - repo: https://github.com/asottile/reorder-python-imports rev: v3.10.0 hooks: - id: reorder-python-imports args: ["--application-directories", "src"] - repo: https://github.com/psf/black rev: 23.7.0 rev: 23.3.0 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 rev: 6.0.0 hooks: - id: flake8 additional_dependencies: - flake8-bugbear7 unmodified linesmodified:CHANGES.rst+8 added-38 removed
1 .. currentmodule:: click2 3-Version 8.1.63+Version 8.2.04 -------------5 6-Released 2023-07-186+Unreleased7 8-- 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.11 12 11-Version 8.1.512--------------13-14-Released 2023-07-1315-16-- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and17- other decorators. Introduce typing tests. :issue:`2558`18-19-13 Version 8.1.414 -------------15 23-Released 2023-07-0616+Unreleased17 18 - 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`23 24 25 Version 8.1.326 -------------1040 unmodified lines