如何使用重命名的变量作为点击选项?

问题描述 投票:0回答:1

我想使用 click 来指定选项,但我想访问不同名称的变量中的值。

这就是我所拥有的

@click.command()
@click.option(
    "--all",
    is_flag=True,
    help="This will use all of it.",
)
def mycode(all):
    ...

但这会覆盖内置函数

all
。因此,为了避免这种情况,我正在寻找一种方法,以便为主代码使用不同的变量,即

@click.command()
@click.option(
    "--all",
    is_flag=True,
    alias="use_all"
    help="This will use all of it.",
)
def mycode(use_all):
    ...

但是 click.option 上的文档似乎非常稀疏/错过了所有内容/我看错了?

那么要怎么做呢?

python python-3.x python-click
1个回答
1
投票

我找到了一种解决方法,即使用多个选项名称并将我们想要的选项名称作为第一个选项放在变量名称中。

import click


@click.command()
@click.option(
    "--use-all",
    "--all",
    is_flag=True,
    help="This will use all of it."
)
def mycode(use_all):
    print(use_all)

它按预期工作并生成此帮助文本:

Usage: so_test.py [OPTIONS]

Options:
  --use-all, --all  This will use all of it.
  --help            Show this message and exit.

这显然不理想。我认为我们可以通过定义我们自己的

Option
类并在
cls=CustomOptionClass
中传递
click.option
来添加它 - 但我没有看到任何关于如何做到这一点的文档。

© www.soinside.com 2019 - 2024. All rights reserved.