rie*_*nix 7 python python-click
所以我想要实现的是确保参数是某些预定义集合(这里是tool1,tool2,tool3)的一部分,就像使用@click.option和type=click.Choice(),同时能够传递多个参数,如@click.argumentwith 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))
Run Code Online (Sandbox Code Playgroud)
这将是这样的例子:
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')
Run Code Online (Sandbox Code Playgroud)
是否有任何内置的方式来实现这一点?或者我应该只使用@click.argument并检查函数本身的输入?
因为我对编程命令行界面很陌生,特别是对于click,并且只是开始深入挖掘python我会很感激如何以一种简洁的方式处理这个问题的建议.
rie*_*nix 11
事实证明我误解了使用multiple=True时的用法@click.option.
例如,可以-t多次调用
python selectTools.py -t tool1 -t tool3 -t tool2
Run Code Online (Sandbox Code Playgroud)
通过使用
@click.option('--tools', '-t', type=click.Choice(['tool1', 'tool2', 'tool3']), multiple=True)
Run Code Online (Sandbox Code Playgroud)
从而可以从可能的选择中选择几种工具.