gpt4 book ai didi

python - Python 单击命令的功能标志

转载 作者:行者123 更新时间:2023-11-28 18:01:45 26 4
gpt4 key购买 nike

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

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

最佳答案

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

自定义类

这个类超越了 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

关于python - Python 单击命令的功能标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55373759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com