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
Parameteris the base class ofoptionandargument.- Positional arguments of
optionandargumentbecomeparam_decl - If a string is added without any dashes, it becomes the parameter name.
- The parameter name is generated automatically by taking the longest argument and converting all dashes to underscores.
@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))- Can modify
ctx.paramsto overwrite other parameters paramis theParameterobjectvalueis the actaul value
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
ClickExceptionis raised, invoke theClickException.show()method on it to display it and then exit the program withClickException.exit_code.
UsageErrorBadParameterFileError
Support auto complete
- To support auto complete of
yhycommand inbash, put the following line to your rc file.
- For
zsh:
Support command aliases howto
Simply copy & pasted from the document
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
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
@click.command(cls=AliasedGroup)
def cli():
pass
@cli.command()
def push():
pass
@cli.command()
def pop():
passNote 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().