Building command line interfaces with click. http://click.pocoo.org
import click
# Basics:
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
# Advanced:
# grouping commands:
@click.group()
def cli():
pass
@click.command()
def initdb():
click.echo('Initialized the database')
@click.command()
def dropdb():
click.echo('Dropped the database')
cli.add_command(initdb)
cli.add_command(dropdb)
# File Arguments
@click.command()
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
def inout(input, output):
while True:
chunk = input.read(1024)
if not chunk:
break
output.write(chunk)
# To hook this up with an automatically updating progress bar, all you need to
# do is to change the code to this:
with click.progressbar(all_the_users_to_process,
label='Modifying user accounts',
length=number_of_users) as bar:
for user in bar:
modify_the_user(user)
@click.command()
# optional:
@click.option('--outdir', default="", help='Specify output directory')
# files argument strictly required
# nargs=-1 == indefinite number of args
@click.argument('files', nargs=-1)
def main(outdir, files):
...
# Prompting
@click.command()
@click.option('--name', prompt='Your name please')
...
# password prompts
@click.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def encrypt(password):
click.echo('Encrypting password to %s' % password.encode('rot13'))
# Range Options
@click.command()
@click.option('--count', type=click.IntRange(0, 20, clamp=True))
@click.option('--digit', type=click.IntRange(0, 10))
def repeat(count, digit):
...
# Click supports prompts in two different places. The first is automated prompts
# when the parameter handling happens, and the second is to ask for prompts at a
# later point independently.
# Input Prompts
value = click.prompt('Please enter a valid integer', type=int)
# Confirmation Prompts
if click.confirm('Do you want to continue?'):
click.echo('Well done!')
# click even offers autocomplete.
# http://click.pocoo.org/5/bashcomplete/
#To enable Bash completion for your foo-bar script, this is what you would
#need to put into your .bashrc:
eval "$(_FOO_BAR_COMPLETE=source foo-bar)
# variadic arguments
# [...] where a specific (or unlimited) number of arguments is accepted.
# This can be controlled with the nargs parameter. If it is set to -1,
# then an unlimited number of arguments is accepted.
@click.command()
@click.argument('files', nargs=-1)
def delete(files):
for f in files:
...