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.
For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.
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() .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With