1 回答
TA贡献1773条经验 获得超3个赞
您可以使用自定义类添加功能标志功能,例如:
自定义类
这个类覆盖了click.Group.command()用于装饰命令函数的方法。它添加了传递active标志的能力,该标志何时False将跳过将命令添加到组中。
import click
class FeatureFlagCommand(click.Group):
def command(self, *args, active=True, **kwargs):
"""Behaves the same as `click.Group.command()` except added an
`active` flag which can be used to disable to command.
"""
if active:
return super(FeatureFlagCommand, self).command(*args, **kwargs)
else:
return lambda f: f
使用自定义类
通过将cls参数传递给click.group()装饰器,任何通过 the 添加到组中的命令group.command()都将使用该active标志进行门控。
@click.group(cls=FeatureFlagCommand)
def cli():
...
@cli.command(name='specialfeature', active=FLAG_ENABLED)
def special_feature_command()
...
这是如何运作的?
这是有效的,因为 click 是一个设计良好的 OO 框架。很容易继承click.Group和构建一个新的command()装饰器。在新的command()装饰器中,如果活动标志是False我们返回未装饰的函数而不是将函数添加到组中。
测试代码:
@click.group(cls=FeatureFlagCommand)
def cli():
"""My Awesome Click Program"""
@cli.command(active=False)
def command1():
click.echo('Command 1')
@cli.command(active=True)
def command2():
click.echo('Command 2')
@cli.command()
def command3():
click.echo('Command 3')
if __name__ == "__main__":
commands = (
'command1',
'command2',
'command3',
'--help',
'',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
cli(cmd.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
结果:
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> command1
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Error: No such command "command1".
-----------
> command2
Command 2
-----------
> command3
Command 3
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
My Awesome Click Program
Options:
--help Show this message and exit.
Commands:
command2
command3
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...
My Awesome Click Program
Options:
--help Show this message and exit.
Commands:
command2
command3
添加回答
举报