gpt4 book ai didi

python - 是否可以在基于 Click 的界面中为所有子命令添加全局参数?

转载 作者:太空狗 更新时间:2023-10-30 00:16:57 36 4
gpt4 key购买 nike

我在 virtualenv 下使用 Click 并使用 entry_point setuptools 中的指令将根映射到一个名为 dispatch 的函数。

我的工具公开了两个子命令 serveconfig ,我在顶级组上使用一个选项来确保用户始终通过 --path指示。然而,用法如下:

mycommand --path=/tmp serve

serveconfig子命令需要确保用户始终传递路径,理想情况下我想将 cli 呈现为:

mycommand serve /tmp` or `mycommand config validate /tmp

当前基于点击的实现如下:

# cli root

@click.group()
@click.option('--path', type=click.Path(writable=True))
@click.version_option(__version__)
@click.pass_context
def dispatch(ctx, path):
"""My project description"""
ctx.obj = Project(path="config.yaml")

# serve

@dispatch.command()
@pass_project
def serve(project):
"""Starts WSGI server using the configuration"""
print "hello"

# config

@dispatch.group()
@pass_project
def config(project):
"""Validate or initalise a configuration file"""
pass

@config.command("validate")
@pass_project
def config_validate(project):
"""Reports on the validity of a configuration file"""
pass

@config.command("init")
@pass_project
def config_init(project):
"""Initialises a skeleton configuration file"""
pass

这是否可以在不向每个子命令添加路径参数的情况下实现?

最佳答案

如果有一个特定的参数你只想装饰到组上,但根据需要适用于所有命令,你可以通过一些额外的管道来做到这一点,比如:

自定义类:

import click

class GroupArgForCommands(click.Group):
"""Add special argument on group to front of command list"""

def __init__(self, *args, **kwargs):
super(GroupArgForCommands, self).__init__(*args, **kwargs)
cls = GroupArgForCommands.CommandArgument

# gather the special arguments
self._cmd_args = {
a.name: a for a in self.params if isinstance(a, cls)}

# strip out the special arguments
self.params = [a for a in self.params if not isinstance(a, cls)]

# hook the original add_command method
self._orig_add_command = click.Group.add_command.__get__(self)

class CommandArgument(click.Argument):
"""class to allow us to find our special arguments"""

@staticmethod
def command_argument(*param_decls, **attrs):
"""turn argument type into type we can find later"""

assert 'cls' not in attrs, "Not designed for custom arguments"
attrs['cls'] = GroupArgForCommands.CommandArgument

def decorator(f):
click.argument(*param_decls, **attrs)(f)
return f

return decorator

def add_command(self, cmd, name=None):

# hook add_command for any sub groups
if hasattr(cmd, 'add_command'):
cmd._orig_add_command = cmd.add_command
cmd.add_command = GroupArgForCommands.add_command.__get__(cmd)
cmd.cmd_args = self._cmd_args

# call original add_command
self._orig_add_command(cmd, name)

# if this command's callback has desired parameters add them
import inspect
args = inspect.signature(cmd.callback)
for arg_name in reversed(list(args.parameters)):
if arg_name in self._cmd_args:
cmd.params[:] = [self._cmd_args[arg_name]] + cmd.params

使用自定义类:

要使用自定义类,将cls参数传递给click.group()装饰器,使用@GroupArgForCommands.command_argument装饰器对于特殊参数,然后根据需要向任何命令添加与特殊参数同名的参数。

@click.group(cls=GroupArgForCommands)
@GroupArgForCommands.command_argument('special')
def a_group():
"""My project description"""

@a_group.command()
def a_command(special):
"""a command under the group"""

这是如何运作的?

之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.group() 装饰器通常实例化一个 click.Group 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Group 并覆盖所需的方法是一件相对容易的事情。

在这种情况下,我们覆盖 click.Group.add_command() 以便在添加命令时我们可以检查命令回调参数以查看它们是否与我们的任何特殊命令具有相同的名称争论。如果它们匹配,则将参数添加到命令的参数中,就好像它已被直接修饰一样。

此外 GroupArgForCommands 实现了一个 command_argument() 方法。在添加特殊参数而不是使用 click.argument()

时,此方法用作装饰器

测试代码:

def process_path_to_project(ctx, cmd, value):
"""param callback example to convert path to project"""
# Use 'path' to construct a project.
# For this example we will just annotate and pass through
return 'converted {}'.format(value)


@click.group(cls=GroupArgForCommands)
@GroupArgForCommands.command_argument('path',
callback=process_path_to_project)
def dispatch():
"""My project description"""


@dispatch.command()
def serve(path):
"""Starts WSGI server using the configuration"""
click.echo('serve {}'.format(path))

@dispatch.group()
def config():
"""Validate or initalise a configuration file"""
pass

@config.command("validate")
def config_validate():
"""Reports on the validity of a configuration file"""
click.echo('config_validate')


@config.command("init")
def config_init(path):
"""Initialises a skeleton configuration file"""
click.echo('config_init {}'.format(path))



if __name__ == "__main__":
commands = (
'config init a_path',
'config init',
'config validate a_path',
'config validate',
'config a_path',
'config',
'serve a_path',
'serve',
'config init --help',
'config validate --help',
'',
)

import sys, time

time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for command in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + command)
time.sleep(0.1)
dispatch(command.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)]
-----------
> config init a_path
config_init converted a_path
-----------
> config init
Usage: test.py config init [OPTIONS] PATH

Error: Missing argument "path".
-----------
> config validate a_path
Usage: test.py config validate [OPTIONS]

Error: Got unexpected extra argument (a_path)
-----------
> config validate
config_validate
-----------
> config a_path
Usage: test.py config [OPTIONS] COMMAND [ARGS]...

Error: No such command "a_path".
-----------
> config
Usage: test.py config [OPTIONS] COMMAND [ARGS]...

Validate or initalise a configuration file

Options:
--help Show this message and exit.

Commands:
init Initialises a skeleton configuration file
validate Reports on the validity of a configuration...
-----------
> serve a_path
serve converted a_path
-----------
> serve
Usage: test.py serve [OPTIONS] PATH

Error: Missing argument "path".
-----------
> config init --help
Usage: test.py config init [OPTIONS] PATH

Initialises a skeleton configuration file

Options:
--help Show this message and exit.
-----------
> config validate --help
Usage: test.py config validate [OPTIONS]

Reports on the validity of a configuration file

Options:
--help Show this message and exit.
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...

My project description

Options:
--help Show this message and exit.

Commands:
config Validate or initalise a configuration file
serve Starts WSGI server using the configuration

关于python - 是否可以在基于 Click 的界面中为所有子命令添加全局参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32493912/

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