单击命令行界面:如果未设置其他可选选项,则需要选项

Dir*_*irk 12 python command-line-interface python-click

在使用Python 点击库编写命令行界面(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()
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 20

这可以通过构建一个自定义类来完成,该类来自于该类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)
Run Code Online (Sandbox Code Playgroud)

使用自定义类:

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

@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?

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

在这种情况下,我们在乘坐click.Option.handle_parse_result()和禁用需要user/password,如果authentication-token令牌存在,并且抱怨,如果两者user/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())
Run Code Online (Sandbox Code Playgroud)

结果:

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

t:None  u:name  p:pword
Run Code Online (Sandbox Code Playgroud)

来自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.
Run Code Online (Sandbox Code Playgroud)


mas*_*asi 8

稍微改进了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)
Run Code Online (Sandbox Code Playgroud)

像这样使用:

@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...")
Run Code Online (Sandbox Code Playgroud)