帮助中列出的命令的顺序由list_commands()
的方法click.Group
班级。因此,满足更改帮助列表顺序的愿望的一种方法是继承click.Group
并覆盖list_commands
给出所需的订单。
定制类
这个类重写了click.Group.command()
用于装饰命令函数的方法。它增加了指定一个的能力help_priority
,它允许根据需要修改排序顺序:
class SpecialHelpOrder(click.Group):
def __init__(self, *args, **kwargs):
self.help_priorities = {}
super(SpecialHelpOrder, self).__init__(*args, **kwargs)
def get_help(self, ctx):
self.list_commands = self.list_commands_for_help
return super(SpecialHelpOrder, self).get_help(ctx)
def list_commands_for_help(self, ctx):
"""reorder the list of commands when listing the help"""
commands = super(SpecialHelpOrder, self).list_commands(ctx)
return (c[1] for c in sorted(
(self.help_priorities.get(command, 1), command)
for command in commands))
def command(self, *args, **kwargs):
"""Behaves the same as `click.Group.command()` except capture
a priority for listing command names in help.
"""
help_priority = kwargs.pop('help_priority', 1)
help_priorities = self.help_priorities
def decorator(f):
cmd = super(SpecialHelpOrder, self).command(*args, **kwargs)(f)
help_priorities[cmd.name] = help_priority
return cmd
return decorator
使用自定义类
通过通过cls
参数到click.group()
装饰器,通过添加到组的任何命令group.command()
可以通过一个help_priority
。优先级默认为 1,首先打印较小的数字。
@click.group(cls=SpecialHelpOrder)
def cli():
"""My Excellent CLI"""
@cli.command(help_priority=5)
def my_command():
....
这是如何运作的?
这是可行的,因为 click 是一个设计良好的 OO 框架。这@click.group()
装饰器通常会实例化一个click.Group
对象,但允许此行为被覆盖cls
范围。所以继承是一件比较容易的事情click.Group
在我们自己的类中并重写所需的方法。
步骤在这里:
- 覆盖
Group.command()
这样修饰后的命令就可以传递help_priority
。在过度使用的装饰器中,捕获所需的优先级以供以后使用
- 覆盖
Group.get_help()
。在重写的方法中,替换Group.list_commands
with a list_commands
这将根据需要对命令进行排序。
测试代码:
import click
@click.group(cls=SpecialHelpOrder)
def cli():
pass
@cli.command()
def command1():
'''Command #1'''
@cli.command(help_priority=5)
def command2():
'''Command #2'''
@cli.command()
def command3():
'''Command #3'''
if __name__ == '__main__':
cli('--help'.split())
检测结果:
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
command1 Command #1
command3 Command #3
command2 Command #2