30

使用 Python click 库编写命令行界面 (CLI) 时,是否可以定义例如三个选项,其中只有第一个(可选)未设置时才需要第二个和第三个选项?

我的用例是一个登录系统,它允许我通过authentication token(选项 1)或通过username(选项 2)和password(选项 3)进行身份验证。

如果给出了令牌,则无需检查usernamepassword定义或提示它们。否则,如果令牌被省略,则成为必需usernamepassword必须给出。

这可以使用回调以某种方式完成吗?

我的入门代码当然不反映预期的模式:

@click.command()
@click.option('--authentication-token', prompt=True, required=True)
@click.option('--username', prompt=True, required=True)
@click.option('--password', hide_input=True, prompt=True, required=True)
def login(authentication_token, username, password):
    print(authentication_token, username, password)

if __name__ == '__main__':
    login()
4

3 回答 3

39

这可以通过构建一个派生自 的自定义类来完成click.Option,并在该类中覆盖以下click.Option.handle_parse_result()方法:

自定义类:

import click

class NotRequiredIf(click.Option):
    def __init__(self, *args, **kwargs):
        self.not_required_if = kwargs.pop('not_required_if')
        assert self.not_required_if, "'not_required_if' parameter required"
        kwargs['help'] = (kwargs.get('help', '') +
            ' NOTE: This argument is mutually exclusive with %s' %
            self.not_required_if
        ).strip()
        super(NotRequiredIf, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        we_are_present = self.name in opts
        other_present = self.not_required_if in opts

        if other_present:
            if we_are_present:
                raise click.UsageError(
                    "Illegal usage: `%s` is mutually exclusive with `%s`" % (
                        self.name, self.not_required_if))
            else:
                self.prompt = None

        return super(NotRequiredIf, self).handle_parse_result(
            ctx, opts, args)

使用自定义类:

要使用自定义类,请将cls参数传递给click.option装饰器,例如:

@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')

这是如何运作的?

这是因为 click 是一个设计良好的 OO 框架。@click.option()装饰器通常实例化一个对象click.Option,但允许使用cls参数覆盖此行为。因此,从click.Option我们自己的类中继承并覆盖所需的方法是一件相对容易的事情。

在这种情况下,如果令牌存在,我们会覆盖click.Option.handle_parse_result()并禁用对令牌的需求,如果两者都存在则抱怨。user/passwordauthentication-tokenuser/passwordauthentication-token

注意:这个答案的灵感来自这个答案

测试代码:

@click.command()
@click.option('--authentication-token')
@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
@click.option('--password', prompt=True, hide_input=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
def login(authentication_token, username, password):
    click.echo('t:%s  u:%s  p:%s' % (
        authentication_token, username, password))

if __name__ == '__main__':
    login('--username name --password pword'.split())
    login('--help'.split())
    login(''.split())
    login('--username name'.split())
    login('--authentication-token token'.split())

结果:

来自login('--username name --password pword'.split())

t:None  u:name  p:pword

来自login('--help'.split())

Usage: test.py [OPTIONS]

Options:
  --authentication-token TEXT
  --username TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --password TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --help                       Show this message and exit.
于 2017-06-03T23:02:35.280 回答
11

略微改进了Stephen Rauch 的答案,使其具有多个互斥体参数。

import click

class Mutex(click.Option):
    def __init__(self, *args, **kwargs):
        self.not_required_if:list = kwargs.pop("not_required_if")

        assert self.not_required_if, "'not_required_if' parameter required"
        kwargs["help"] = (kwargs.get("help", "") + "Option is mutually exclusive with " + ", ".join(self.not_required_if) + ".").strip()
        super(Mutex, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        current_opt:bool = self.name in opts
        for mutex_opt in self.not_required_if:
            if mutex_opt in opts:
                if current_opt:
                    raise click.UsageError("Illegal usage: '" + str(self.name) + "' is mutually exclusive with " + str(mutex_opt) + ".")
                else:
                    self.prompt = None
        return super(Mutex, self).handle_parse_result(ctx, opts, args)

像这样使用:

@click.group()
@click.option("--username", prompt=True, cls=Mutex, not_required_if=["token"])
@click.option("--password", prompt=True, hide_input=True, cls=Mutex, not_required_if=["token"])
@click.option("--token", cls=Mutex, not_required_if=["username","password"])
def login(ctx=None, username:str=None, password:str=None, token:str=None) -> None:
    print("...do what you like with the params you got...")
于 2018-07-08T20:03:05.280 回答
0

这是另一个变体,其中 has not_required_if 必须使用 snake_case 变体指定,使用 required 而不是提示符,重要的是,如果其他参数是通过环境变量而不是在命令行上使用 ctx.command.get_params 传递的,它可以工作(...) 和 param.consume_value(...):

import click


class Mutex(click.Option):
    def __init__(self, *args, **kwargs):
        self.not_required_if: list = kwargs.pop("not_required_if")

        assert self.not_required_if, "'not_required_if' parameter required"
        kwargs["help"] = (kwargs.get("help", "") + "Option is mutually exclusive with " + ", ".join(self.not_required_if) + ".").strip()
        super(Mutex, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        current_opt: bool = self.consume_value(ctx, opts)
        for other_param in ctx.command.get_params(ctx):
            if other_param is self:
                continue
            if other_param.human_readable_name in self.not_required_if:
                other_opt: bool = other_param.consume_value(ctx, opts)
                if other_opt:
                    if current_opt:
                        raise click.UsageError(
                            "Illegal usage: '" + str(self.name)
                            + "' is mutually exclusive with "
                            + str(other_param.human_readable_name) + "."
                        )
                    else:
                        self.required = None
        return super(Mutex, self).handle_parse_result(ctx, opts, args)
于 2020-05-08T17:19:38.963 回答