Search code examples
pythoncommand-line-interfacepython-click

Ignoring empty arguments for certain flags


I have a command that takes 1 argument and can take several flags.

@click.command()
@click.argument('item')
@click.option('--list-items', help='list items', is_flag=True)
def cli(item, list_items):
    if list_items:
        click.echo(ITEMS)
        return

currently it returns:

Error: Missing argument "item".

How can I make so that I could access the functionality of --list-items even if I don't provide an argument? Just like --help flag does.


Solution

  • You'd have to make item optional:

    @click.argument('item', required=False)
    

    then do error handling in the function (e.g. raise a BadParameter() exeception).