Skip to content

Instantly share code, notes, and snippets.

@mountcedar
Last active December 16, 2015 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mountcedar/94a64d3b144fab9bd287 to your computer and use it in GitHub Desktop.
Save mountcedar/94a64d3b144fab9bd287 to your computer and use it in GitHub Desktop.
python clickでサブコマンドを簡単に実装する ref: http://qiita.com/mountcedar/items/45b06ce58b1d2ae001f3
$ pip install click
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()
Usage: sample.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
subcommand1 description 1
subcommand2 description 2
...
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):
...
$ python ./sample.py shortcut
gonna invoke shortcut
sub command 1
@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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment