Python单击命令的功能标志

时间:2019-03-27 09:28:21

标签: python python-click

在我的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:
        ...

但是我的命令仍然会显示在帮助中,我想避免。

1 个答案:

答案 0 :(得分:1)

您可以使用以下自定义类添加功能标记功能:

自定义类

该类超越了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()装饰器,通过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