Skip to content

Instantly share code, notes, and snippets.

@orbitbot
Created June 14, 2015 19:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orbitbot/ffd5eb9df5fde0655e67 to your computer and use it in GitHub Desktop.
Save orbitbot/ffd5eb9df5fde0655e67 to your computer and use it in GitHub Desktop.
Default subcommands with Python Click command line parser
import click
class DefaultCmdGroup(click.Group):
def get_command(self, ctx, cmd_name):
click.echo(ctx.args)
cmd = click.Group.get_command(self, ctx, cmd_name)
if cmd is not None:
return cmd
else:
return click.Group.get_command(self, ctx, 'send')
@click.command(cls=DefaultCmdGroup)
@click.pass_context
def main(ctx):
pass
@click.command(help='Send recipient a message')
@click.argument('recipient')
@click.argument('message', nargs=-1)
@click.pass_context
def send(ctx, recipient, message):
if ctx.parent.args[0] != 'send':
recipient = ctx.parent.args[0]
msg = ' '.join(ctx.parent.args[1:])
else:
msg = ' '.join(list(message))
click.echo('send ' + recipient + ' ' + msg)
@JoshuaEnglish
Copy link

This may be for an older version of Click, but I couldn't get this to work on Click 6 and Python 3.6. The send command isn't recognized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment