Click

Table of Contents

Overview

@click.command()
@click.option('--count', default=1, help='number of greetings')
@click.argument('name')
def hello(count, name):
    for x in range(count):
        click.echo('Hello %s!' % name)
@click.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

Reference

echo, secho

click.echo('Hello World!')
click.echo(b'\xe2\x98\x83', nl=False)
click.echo('Hello World!', err=True)

click.secho('Hello World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

option

@click.option('--n', default=1)
@click.option('--pos', nargs=2, type=float)
@click.option('--item', type=(unicode, int))
@click.option('--message', '-m', multiple=True)  #  -m foo -m bar
@click.option('--shout/--no-shout', default=False)
@click.option('--shout', is_flag=True)
@click.option('--hash-type', type=click.Choice(['md5', 'sha1']))
@click.option('--name', prompt='Your name please')
@click.option('--username', envvar='USERNAME')

paramdecls

@click.option('-v', count=True)
def foo(v):

@click.option('-v', '--verbose', count=True)  # longest n
def foo(verbose):

@click.option('vvv', '-v', '--verbose', count=True)
def foo(vvv):

Path

class click.Path(exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False)

callback

import urllib

def open_url(ctx, param, value):
    if value is not None:
        ctx.params['fp'] = urllib.urlopen(value)
        return value

@click.command()
@click.option('--url', callback=open_url)
def cli(url, fp=None):
    if fp is not None:
        click.echo('%s: %s' % (url, fp.code))

Samples

Arguments

@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
@click.argument('f', type=click.Path(exists=True))
@click.argument('src', envvar='SRC', type=click.File('r'))
@click.argument('files', nargs=-1, type=click.Path())

How-to

Handle exceptions

click.Abort just exits with code 1, shows nothing but a message Aborted!.

It seems okay to just use sys.exit(), but there are some click exceptions available to handle it with default behaviors.

If an ClickException is raised, invoke the ClickException.show() method on it to display it and then exit the program with ClickException.exit_code.

Support auto complete

eval "$(_YHY_COMPLETE=source yhy)"
autoload -Uz bashcompinit && bashcompinit
eval "$(_YHY_COMPLETE=source yhy)"

Support command aliases howto

Simply copy & pasted from the document

Note the code uses @click.command(cls=AliasedGroup) instead of @click.group() or something. Actually, @click.group() is just a short name for @click.command(cls=Gorup). So, when you need to customize group things, you should use @click.command().