使用 Python 编写命令行界面 (CLI) 时 click library , 是否可以定义例如三个选项,其中仅当第一个(可选)未设置时才需要第二个和第三个选项?
我的用例是一个登录系统,它允许我通过 authentication token
(选项 1)或通过 username
(选项 2)进行身份验证) 和 password
(选项 3)。
如果提供了 token ,则无需检查是否定义了 username
和 password
或提示它们。否则,如果 token 被省略,则 username
和 password
将变为必需且必须提供。
可以使用回调以某种方式完成吗?
我的入门代码当然没有反射(reflect)预期的模式:
@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()
最佳答案
这可以通过构建一个派生自 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/password
if authentication-token
token 的需要存在,如果 user/password
和 authentication-token
都存在,则提示。
注意:此答案的灵感来自 this answer
测试代码:
@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.
关于python - 单击命令行界面 : Make options required if other optional option is unset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247099/