提供一些别名的一种方法是拦截命令并直接操作args
列表。这可以通过自定义类来完成,例如:
定制类
这个类重写了click.Group.__call__()
方法允许编辑args
在调用命令处理器之前列出。此外它还覆盖format_epilog
添加别名的帮助文档。
class ExpandAliasesGroup(click.Group):
def __init__(self, *args, **kwargs):
self.aliases = kwargs.pop('aliases', {})
super(ExpandAliasesGroup, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if args and args[0] and args[0][0] in self.aliases:
alias = self.aliases[args[0][0]]
args[0].pop(0)
for command in reversed(alias):
args[0].insert(0, command)
return super(ExpandAliasesGroup, self).__call__(*args, **kwargs)
@property
def alias_help(self):
return '\n'.join(
'{}: {}'.format(alias, ' '.join(commands))
for alias, commands in sorted(self.aliases.items())
)
def format_epilog(self, ctx, formatter):
"""Inject our aliases into the help string"""
if self.aliases:
formatter.write_paragraph()
formatter.write_text('Aliases:')
with formatter.indentation():
formatter.write_text(self.alias_help)
# call the original epilog
super(ExpandAliasesGroup, self).format_epilog(ctx, formatter)
使用自定义类
通过通过cls
参数,以及别名的字典click.group()
装饰师,ExpandAliasesGroup
类可以进行别名扩展。
aliases = dict(all='command1 command2 command3'.split())
@click.group(chain=True, cls=ExpandAliasesGroup, aliases=aliases)
def cli():
....
这是如何运作的?
这是可行的,因为 click 是一个设计良好的 OO 框架。这@click.group()
装饰器通常会实例化一个click.Group
对象,但允许此行为被覆盖cls
范围。所以继承是一件比较容易的事情click.Group
在我们自己的类中并重写所需的方法。
通过重写__call__
方法我们可以拦截所有命令调用。然后,如果参数列表以已知别名开头,我们通过删除该别名命令并将其替换为别名来编辑参数列表。
通过重写format_epilog
方法我们可以为别名添加帮助文档。
测试代码:
import click
aliases = dict(all='command1 command2 command3'.split())
@click.group(cls=ExpandAliasesGroup, chain=True, aliases=aliases)
def cli():
pass
@cli.command()
def command1():
click.echo('Command 1')
@cli.command()
def command2():
click.echo('Command 2')
@cli.command()
def command3():
click.echo('Command 3')
if __name__ == "__main__":
commands = (
'command1',
'command3',
'command1 command2',
'all',
'--help',
)
for cmd in commands:
try:
print('-----------')
print('> ' + cmd)
cli(cmd.split())
except:
pass
检测结果:
-----------
> command1
Command 1
-----------
> command3
Command 3
-----------
> command1 command2
Command 1
Command 2
-----------
> all
Command 1
Command 2
Command 3
-----------
> --help
Usage: test.py [OPTIONS] COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...
Options:
--help Show this message and exit.
Commands:
command1 Command #1 comes first
command2 Command #2 is after command #1
command3 Command #3 saves the best for last
Aliases:
all: command1 command2 command3