【发布时间】:2022-02-13 02:50:52
【问题描述】:
我正在尝试将 argparse 命令行界面 (CLI) 移植到 click。此 CLI 必须保持用户提供参数的顺序。在argparse 版本中,我使用this StackOverflow answer 来维护秩序。对于click,我不知道该怎么做。
我尝试创建一个自定义回调来按顺序存储参数和值,但是如果多次使用一个参数,回调会在它第一次看到匹配的参数时触发。
import click
import typing
class OrderParams:
_options: typing.List[typing.Tuple[click.Parameter, typing.Any]] = []
@classmethod
def append(cls, ctx: click.Context, param: click.Parameter, value: typing.Any):
cls._options.append((param, value))
@click.command()
@click.option("--animal", required=True, multiple=True, callback=OrderParams.append)
@click.option("--thing", required=True, multiple=True, callback=OrderParams.append)
def cli(*, animal, thing):
click.echo("Got this order of parameters:")
for param, value in OrderParams._options:
print(" ", param.name, value)
if __name__ == "__main__":
cli()
电流输出:
$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
animal ('cat', 'dog')
thing ('rock',)
期望的输出:
$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
animal 'cat'
thing 'rock'
animal 'dog'
click documentation describes the behavior 表示第一次遇到参数时调用一次回调,即使该参数被多次使用。
如果一个选项或参数在命令行上被拆分为多个位置,因为它是重复的 [...] 回调将根据第一个选项的位置触发。
【问题讨论】:
标签: python command-line-interface python-click