class CustomMultiCommand(click.Group):
def command(self, *args, **kwargs):
"""Behaves the same as `click.Group.command()` except if passed
a list of names, all after the first will be aliases for the first.
"""
def decorator(f):
if isinstance(args[0], list):
_args = [args[0][0]] + list(args[1:])
for alias in args[0][1:]:
cmd = super(CustomMultiCommand, self).command(
alias, *args[1:], **kwargs)(f)
cmd.short_help = "Alias for '{}'".format(_args[0])
else:
_args = args
cmd = super(CustomMultiCommand, self).command(
*_args, **kwargs)(f)
return cmd
return decorator
import click
@click.group(cls=CustomMultiCommand)
def cli():
"""My Excellent CLI"""
@cli.command(['my-command', 'my-cmd'])
def my_command():
"""This is my command"""
print('Running the command')
if __name__ == '__main__':
cli(' help'.split())
测试结果:
Usage: my_cli [OPTIONS] COMMAND [ARGS]...
My Excellent CLI
Options:
help Show this message and exit.
Commands:
my-cmd Alias for 'my-command'
my-command This is my command
这里有一个更简单的方法来解决同样的问题:
AliasedGroup不是您所追求的,因为它允许最短的前缀匹配,而且您似乎需要实际的别名。但这个例子确实提供了一些有用的提示。它继承了
click.Group
并覆盖了一些行为。在以下是一种接近你所追求目标的方法:
自定义类
这个类覆盖了用来修饰命令函数的
click.Group.command()
方法。它增加了传递命令别名列表的功能。这个类还添加了一个引用别名命令的简短帮助。在使用自定义类
通过将
^{pr2}$cls
参数传递给click.group()
修饰符,通过group.command()
添加到组中的任何命令都可以传递一个命令名列表。在测试代码:
测试结果:
相关问题 更多 >
编程相关推荐