click.Choice for multiple arguments
Asked Answered
H

1

30

So what I want to achieve is to both assure that the arguments are part of certain predefined set (here tool1, tool2, tool3), like with @click.option and type=click.Choice(), and at the same time to be able to pass multiple arguments like with @click.argument with nargs=-1.

import click

@click.command()
@click.option('--tools', type=click.Choice(['tool1', 'tool2', 'tool3']))
@click.argument('programs', nargs=-1)
def chooseTools(programs, tools):
    """Select one or more tools to solve the task"""

    # Selection of only one tool, but it is from the predefined set
    click.echo("Selected tools with 'tools' are {}".format(tools))

    # Selection of multiple tools, but no in-built error handling if not in set
    click.echo("Selected tools with 'programs' are {}".format(programs))

This would look for example like this:

python selectTools.py --tools tool1 tool3 tool2 nonsense
Selected tools with 'tools' are tool1
Selected tools with 'programs' are (u'tool3', u'tool2', u'nonsense')

Is there any built-in way in click to achieve that? Or should I just use @click.argument and check the input in the function itself?

As I am rather new to programming command-line interfaces, especially with click, and only starting to dig deeper in python I would appreciate recommendations for how to handle this problem in a neat manner.

Hysteric answered 27/5, 2016 at 14:43 Comment(0)
H
35

As it turns out I misunderstood the usage of multiple=True when using @click.option.

For example is it possible to invoke -t multiple times

python selectTools.py -t tool1 -t tool3 -t tool2

by using

@click.option('--tools', '-t', type=click.Choice(['tool1', 'tool2', 'tool3']), multiple=True)

and thus makes the selection of several tools from the choices possible.

Hysteric answered 3/6, 2016 at 21:41 Comment(1)
You can also write python selectTools.py --tools={tool1,tool2,tool3}Broads

© 2022 - 2024 — McMap. All rights reserved.