The order of the commands listed by help is set by the list_commands()
method of the click.Group
class. So, one way to approach the desire to change the help listing order is to inherit for click.Group
and override list_commands
to give the desired order.
Custom Class
This class overrides the click.Group.command()
method which is used to decorate command functions. It adds the ability to specify a help_priority
, which allows the sort order to be modified as desired:
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
Using the Custom Class
By passing the cls
parameter to the click.group()
decorator, any commands added to the group via the the group.command()
can be passed a help_priority
. The priorities default to 1, and lower numbers are printed first.
@click.group(cls=SpecialHelpOrder)
def cli():
"""My Excellent CLI"""
@cli.command(help_priority=5)
def my_command():
....
How does this work?
This works because click is a well designed OO framework. The @click.group()
decorator usually instantiates a click.Group
object but allows this behavior to be over ridden with the cls
parameter. So it is a relatively easy matter to inherit from click.Group
in our own class and over ride the desired methods.
Steps here:
- Override
Group.command()
so that decorated commands can be passed a help_priority
. In the over ridden decorator, capture the desired priority for later
- Override
Group.get_help()
. In the over ridden method, substitute Group.list_commands
with a list_commands
which will order the commands as desired.
Test Code:
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())
Test Results:
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
command1 Command #1
command3 Command #3
command2 Command #2