In Qiita's comment, when I checked the click that was introduced, I found that it was easy to implement subcommands, so I will summarize how to do it. A subcommand is a command in which the first argument of the script is a command, which is a format found in version control commands such as git and svn, and django's project management script manage.py.
click is not a standard python package, so install it with pip.
$ pip install click
The basic code looks like this:
import click
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
if ctx.invoked_subcommand is None:
print ctx.get_help()
else:
print('gonna invoke %s' % ctx.invoked_subcommand)
@cli.command(help='description 1')
@click.argument('target', required=False)
def subcommand1(target):
print "sub command 1"
@cli.command(help='description 2')
@click.argument('target', required=False)
def subcommand2(target):
print "sub command 2"
if __name__ == '__main__': cli()
cli is the starting function for everything, and subcommand1 and subcommand2 are the implementations of the subcommands, respectively. Enter each description as a help variable in @ cli.command. The following shows the contents of the command help displayed.
Usage: sample.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
subcommand1 description 1
subcommand2 description 2
You can see that subcommands 1 and 2 are registered in Commands.
Tips
(Sub) The command name may be too long and you may want to create a shortcut command. In that case, extend the Group class and implement it.
...
class AliasedGroup(click.Group):
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
if cmd_name == 'shortcut':
return click.Group.get_command(self, ctx, 'subcommand1')
return None
@click.group(cls=AliasedGroup, invoke_without_command=True)
@click.pass_context
def cli(ctx):
...
As above, specify the AliasedGroup implemented as the cls argument of @ click.group. Then
$ python ./sample.py shortcut
gonna invoke shortcut
sub command 1
The implementation of sabcommand1 works as above.
If you want to divide into multiple files and implement subcommands, you can implement the command and add it to the group.
@click.group(invoke_without_command=True)
@click.pass_context
def handle(ctx):
if ctx.invoked_subcommand is None:
print ctx.get_help()
else:
print('gonna invoke %s' % ctx.invoked_subcommand)
@click.command()
def hoge():
pass
handle.add_command(hoge)
As soon as I try it, I would like to introduce the implementation of concatenated commands.
Recommended Posts