Arguments express what a command operates on, like files or names, which is how users expect Unix tools to work.
@click.argument("src") declares a positional parameter. Arguments are required by default and are matched by position, in decorator order.
nargs=-1accepts any number of values into a tuple, likecp's list of sources:@click.argument("files", nargs=-1). Only one argument can be variadic. Addrequired=Trueif at least one value is needed.type=works as for options:int,click.Path(exists=True),click.File("r"),click.Choice([...]).required=Falseor adefault=makes an argument optional.- Since Click 8.5, arguments accept
help=text, shown in a "Positional arguments" section of--help. Before that, arguments were documented only in the command's docstring, which is still a good habit.
Arguments names are shown in uppercase in the usage line: Usage: copy [OPTIONS] SRC... DST.
When to choose which: use arguments for the primary objects of a command (the file to read, the user to delete), and options for everything that modifies behaviour. Avoid more than two or three arguments; long positional lists are hard to remember, while named options are self-documenting.
A common trick for values that start with a dash, like negative numbers or file names such as -data.txt: users can put -- before them, which tells Click that everything after it is positional.
Example
import click
@click.command()
@click.argument("sources", nargs=-1, required=True)
@click.argument("dest")
@click.option("--dry-run", is_flag=True)
def copy(sources, dest, dry_run):
"""Copy SOURCES... to DEST."""
for src in sources:
click.echo(f"{'would copy' if dry_run else 'copy'} {src} -> {dest}")
copy.main(["a.txt", "b.txt", "backup/", "--dry-run"], standalone_mode=False)
# would copy a.txt -> backup/
# would copy b.txt -> backup/
copy.main(["--", "-odd-name.txt", "backup/"], standalone_mode=False)
# copy -odd-name.txt -> backup/Remember
- Arguments are positional and required by default
- nargs=-1 collects any number of values into a tuple
- Use arguments for what the command acts on, options for how
Watch out for
- Using several positional arguments where named options would be clearer.