Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
30e907c
Rough out changes to arguments section.
Rowlando13 Aug 14, 2023
fb325a4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 14, 2023
63c03ab
Revert random file changes made by git.
Rowlando13 Aug 14, 2023
ba5b4ce
Merge branch 'trim_args_section' of https://github.com/Rowlando13/cli…
Rowlando13 Aug 14, 2023
c2e6f2e
Merge branch '8.1.x' of https://github.com/Rowlando13/click into trim…
Rowlando13 Aug 28, 2023
f0f5ce1
Fix capitalization.
Rowlando13 Aug 28, 2023
82ffa4b
Merge branch 'stable' of https://github.com/Rowlando13/click into tri…
Rowlando13 Nov 8, 2024
424d0e7
Rewrite arguments docs more nicely.
Rowlando13 Nov 8, 2024
e26d89d
Fix broken admonition block.
Rowlando13 Nov 8, 2024
273fb90
More robust check of bash version (#2639)
koliyo Nov 9, 2024
50bfe23
Cleanup handling files documentation.
Rowlando13 Nov 13, 2024
e835913
Clarify environment variables section.
Rowlando13 Nov 14, 2024
e0f59be
More concisely phrase Environment Variables section.
Rowlando13 Nov 14, 2024
e9a76ba
Fix a typo in File Opening Behaviors.
Rowlando13 Nov 28, 2024
70c673d
Fix eagerness of help option generated by `help_option_names` (#2811)
kdeldycke Nov 30, 2024
299efb8
Use subprocess instead of os.system (#1477)
jwodder Nov 30, 2024
9959aa9
Apply suggestions from code review for arguments docs.
Rowlando13 Dec 4, 2024
9ce8bd8
add additional issues to changelog
davidism Dec 4, 2024
ffd43e9
Fixed missing reset on _compat.should_strip_ansi.
Tyl13 May 22, 2024
fdc6b02
Fix missing reset in isolation function (#2733)
davidism Dec 4, 2024
b1e392e
fix typos
davidism Dec 4, 2024
6534590
update dev dependencies
davidism Dec 4, 2024
bed0377
remove test pypi
davidism Dec 4, 2024
3241541
Remove some typing hints.
Rowlando13 Dec 5, 2024
8e7bed0
Break up arguments section (#2586)
Rowlando13 Dec 5, 2024
822d4fd
Add links to third-party projects
kdeldycke Dec 7, 2024
c23223b
Add links to third-party projects enhancing Click (#2815)
Rowlando13 Dec 7, 2024
934813e
release version 8.1.8
AndreasBackx Dec 19, 2024
4cef966
release version 8.1.8 (#2826)
davidism Dec 21, 2024
b605b7b
Merge branch 'stable'
AndreasBackx Dec 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,6 @@ jobs:
id-token: write
steps:
- uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
- uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3
with:
repository-url: https://test.pypi.org/legacy/
packages-dir: artifact/
- uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3
- uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2
with:
packages-dir: artifact/
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.1
rev: v0.8.1
hooks:
- id: ruff
- id: ruff-format
Expand Down
15 changes: 14 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ Unreleased
Version 8.1.8
-------------

Unreleased
Released 2024-12-19

- Fix an issue with type hints for ``click.open_file()``. :issue:`2717`
- Fix issue where error message for invalid ``click.Path`` displays on
Expand All @@ -112,6 +112,19 @@ Unreleased
:issue:`2632`
- Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be
forced on Windows. :issue:`2606`.
- More robust bash version check, fixing problem on Windows with git-bash.
:issue:`2638`
- Cache the help option generated by the ``help_option_names`` setting to
respect its eagerness. :pr:`2811`
- Replace uses of ``os.system`` with ``subprocess.Popen``. :issue:`1476`
- Exceptions generated during a command will use the context's ``color``
setting when being displayed. :issue:`2193`
- Error message when defining option with invalid name is more descriptive.
:issue:`2452`
- Refactor code generating default ``--help`` option to deduplicate code.
:pr:`2563`
- Test ``CLIRunner`` resets patched ``_compat.should_strip_ansi``.
:issue:`2732`


Version 8.1.7
Expand Down
236 changes: 64 additions & 172 deletions docs/arguments.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,195 +5,118 @@ Arguments

.. currentmodule:: click

Arguments work similarly to :ref:`options <options>` but are positional.
They also only support a subset of the features of options due to their
syntactical nature. Click will also not attempt to document arguments for
you and wants you to :ref:`document them manually <documenting-arguments>`
in order to avoid ugly help pages.
Arguments are:

* Are positional in nature.
* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs
* :ref:`Documented manually <documenting-arguments>`.

Useful and often used kwargs are:

* ``default``: Passes a default.
* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.

Basic Arguments
---------------

The most basic option is a simple string argument of one value. 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 :data:`STRING`.
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``.

Example:

.. click:example::

@click.command()
@click.argument('filename')
def touch(filename):
def touch(filename: str):
"""Print FILENAME."""
click.echo(filename)

And what it looks like:
And from the command line:

.. click:run::

invoke(touch, args=['foo.txt'])

Variadic Arguments
------------------

The second most common version is variadic arguments where a specific (or
unlimited) number of arguments is accepted. This can be controlled with
the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number
of arguments is accepted.
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`.

The value is then passed as a tuple. Note that only one argument can be
set to ``nargs=-1``, as it will eat up all arguments.
.. admonition:: Note on Required Arguments

Example:
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.

Multiple Arguments
-----------------------------------

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.

.. click:example::

@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def copy(src, dst):
@click.argument('src', nargs=1)
@click.argument('dsts', nargs=-1)
def copy(src: str, dsts: tuple[str, ...]):
"""Move file SRC to DST."""
for fn in src:
click.echo(f"move {fn} to folder {dst}")
for destination in dsts:
click.echo(f"Copy {src} to folder {destination}")

And what it looks like:
And from the command line:

.. click:run::

invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])

Note that this is not how you would write this application. The reason
for this is that in this particular example the arguments are defined as
strings. Filenames, however, are not strings! They might be on certain
operating systems, but not necessarily on all. For better ways to write
this, see the next sections.
invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])

.. admonition:: Note on Non-Empty Variadic Arguments
.. admonition:: Note on Handling Files

If you come from ``argparse``, you might be missing support for setting
``nargs`` to ``+`` to indicate that at least one argument is required.
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.

This is supported by setting ``required=True``. However, this should
not be used if you can avoid it as we believe scripts should gracefully
degrade into becoming noops if a variadic argument is empty. The
reason for this is that very often, scripts are invoked with wildcard
inputs from the command line and they should not error out if the
wildcard is empty.
Argument Escape Sequences
---------------------------

.. _file-args:
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.

File Arguments
--------------

Since all the examples have already worked with filenames, it makes sense
to explain how to deal with files properly. Command line tools are more
fun if they work with files the Unix way, which is to accept ``-`` as a
special file that refers to stdin/stdout.

Click supports this through the :class:`click.File` type which
intelligently handles files for you. It also deals with Unicode and bytes
correctly for all versions of Python so your script stays very portable.

Example:
Example usage:

.. click:example::

@click.command()
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
def inout(input, output):
"""Copy contents of INPUT to OUTPUT."""
while True:
chunk = input.read(1024)
if not chunk:
break
output.write(chunk)

And what it does:

.. click:run::
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
"""Print all FILES file names."""
for filename in files:
click.echo(filename)

with isolated_filesystem():
invoke(inout, args=['-', 'hello.txt'], input=['hello'],
terminate_input=True)
invoke(inout, args=['hello.txt', '-'])
And from the command line:

File Path Arguments
-------------------
.. click:run::

In the previous example, the files were opened immediately. But what if
we just want the filename? The naïve way is to use the default string
argument type. The :class:`Path` type has several checks available which raise nice
errors if they fail, such as existence. Filenames in these error messages are formatted
with :func:`format_filename`, so any undecodable bytes will be printed nicely.
invoke(touch, ['--', '-foo.txt', 'bar.txt'])

Example:
If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:

.. click:example::

@click.command()
@click.argument('filename', type=click.Path(exists=True))
def touch(filename):
"""Print FILENAME if the file exists."""
click.echo(click.format_filename(filename))
@click.command(context_settings={"ignore_unknown_options": True})
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
"""Print all FILES file names."""
for filename in files:
click.echo(filename)

And what it does:
And from the command line:

.. click:run::

with isolated_filesystem():
with open('hello.txt', 'w') as f:
f.write('Hello World!\n')
invoke(touch, args=['hello.txt'])
println()
invoke(touch, args=['missing.txt'])


File Opening Safety
-------------------

The :class:`FileType` type has one problem it needs to deal with, and that
is to decide when to open a file. The default behavior is to be
"intelligent" about it. What this means is that it will open stdin/stdout
and files opened for reading immediately. This will give the user direct
feedback when a file cannot be opened, but it will only open files
for writing the first time an IO operation is performed by automatically
wrapping the file in a special wrapper.

This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to
the constructor. If the file is opened lazily, it will fail its first IO
operation by raising an :exc:`FileError`.

Since files opened for writing will typically immediately empty the file,
the lazy mode should only be disabled if the developer is absolutely sure
that this is intended behavior.

Forcing lazy mode is also very useful to avoid resource handling
confusion. If a file is opened in lazy mode, it will receive a
``close_intelligently`` method that can help figure out if the file
needs closing or not. This is not needed for parameters, but is
necessary for manually prompting with the :func:`prompt` function as you
do not know if a stream like stdout was opened (which was already open
before) or a real file that needs closing.

Starting with Click 2.0, 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.
invoke(touch, ['-foo.txt', 'bar.txt'])


.. _environment-variables:

Environment Variables
---------------------

Like options, arguments can also grab values from an environment variable.
Unlike options, however, this is only supported for explicitly named
environment variables.
Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.

Example usage:
Checking one environment variable:

.. click:example::

Expand All @@ -208,59 +131,28 @@ And from the command line:
.. click:run::

with isolated_filesystem():
# Writing the file in the filesystem.
with open('hello.txt', 'w') as f:
f.write('Hello World!')
invoke(echo, env={'SRC': 'hello.txt'})

In that case, it can also be a list of different environment variables
where the first one is picked.

Generally, this feature is not recommended because it can cause the user
a lot of confusion.

Option-Like Arguments
---------------------

Sometimes, you want to process arguments that look like options. For
instance, imagine you have a file named ``-foo.txt``. If you pass this as
an argument in this manner, Click will treat it as an option.

To solve this, Click does what any POSIX style command line script does,
and that is to accept the string ``--`` as a separator for options and
arguments. After the ``--`` marker, all further parameters are accepted as
arguments.

Example usage:
Checking multiple environment variables:

.. click:example::

@click.command()
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
"""Print all FILES file names."""
for filename in files:
click.echo(filename)

And from the command line:

.. click:run::

invoke(touch, ['--', '-foo.txt', 'bar.txt'])

If you don't like the ``--`` marker, you can set ignore_unknown_options to
True to avoid checking unknown options:

.. click:example::

@click.command(context_settings={"ignore_unknown_options": True})
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
"""Print all FILES file names."""
for filename in files:
click.echo(filename)
@click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))
def echo(src):
"""Print value of SRC environment variable."""
click.echo(src.read())

And from the command line:

.. click:run::

invoke(touch, ['-foo.txt', 'bar.txt'])
with isolated_filesystem():
# Writing the file in the filesystem.
with open('hello.txt', 'w') as f:
f.write('Hello World from second variable!')
invoke(echo, env={'SRC_2': 'hello.txt'})
Loading