Click allows for variadic arguments like this:
@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def copy(src, dst):
"""Move file SRC to DST."""
for fn in src:
click.echo(f"move {fn} to folder {dst}")
But how can I specify at most one argument? While it may be interesting to have a minimum and maximum number, I am looking for adding an optional argument.
I think nargs=-1 and checking if n<2 myself would work like this
@click.command()
@click.argument('some_argument')
@click.argument('optional_argument', nargs=-1)
def example(some_argument, optional_argument):
if len(option_argument) > 1:
print("Too many arguments")
return
# do something with or without the optional argument
but the automatically generated helptext then just should some_argument optional_argument... and it should indicate it by some_argument [optional_argument]. And of course it would be nice if click could handle the check itself instead of only checking for zero or more arguments.