Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click.Choice for multiple arguments

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.

like image 773
rienix Avatar asked May 27 '16 14:05

rienix


People also ask

How do you click multiple options?

For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

What is click Pass_context?

When a Click command callback is executed, it's passed all the non-hidden parameters as keyword arguments. Notably absent is the context. However, a callback can opt into being passed to the context object by marking itself with pass_context() .

What is Click option in Python?

Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the “Command Line Interface Creation Kit”. It's highly configurable but comes with sensible defaults out of the box.


1 Answers

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.

like image 200
rienix Avatar answered Oct 24 '22 00:10

rienix