Python 单击命令的功能标志

Feature flag for Python click commands

在我的 python-click-CLI 脚本中,我正在为用户不可见的功能构建一些命令(以免混淆),但对于例如用户可见。开发商。

是否可以为 Python-单击命令使用功能标志?

我希望能够配置(通过配置文件等)命令是否可用。如果命令功能被禁用,则该命令不应该被调用,帮助也不应该显示它。

像这样:

FLAG_ENABLED = False

# This command should not be shown and not be callable as long as the flag is disabled
@cli.command(name='specialfeature', active=FLAG_ENABLED)
def special_feature_command()
    ....

显然,我可以更改函数的主体:

@cli.command(name='specialfeature', active=FLAG_ENABLED)
def special_feature_command()
    if FLAG_ENABLED:
        ...
    else:
        ...

但是我的命令仍然会出现在帮助中,我想避免这种情况。

您可以使用自定义 class 添加 功能标志 功能,例如:

自定义Class

此 class 覆盖了用于修饰命令函数的 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

使用自定义 Class

通过将 cls 参数传递给 click.group() 装饰器,任何通过 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 我们 return 未装饰的函数而不是将函数添加到组中。

测试代码:

@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