click.Choice 对于多个参数

click.Choice for multiple arguments

所以我想要实现的是确保参数是某些预定义集(这里是 tool1、tool2、tool3)的一部分,就像 @click.optiontype=click.Choice() 一样,并且在同时能够传递多个参数,例如 @click.argumentnargs=-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))

这看起来像这样的例子:

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')

click 中有没有内置的方法来实现这一点? 或者我应该只使用 @click.argument 并检查函数本身的输入吗?

由于我对命令行界面编程相当陌生,尤其是点击,并且只是开始更深入地研究 python 我将不胜感激有关如何以简洁的方式处理此问题的建议。

事实证明我在使用@click.option时误解了multiple=True的用法。

例如,是否可以多次调用 -t

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

通过使用

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

因此可以从选项中选择多个工具。