Skip to content

Instantly share code, notes, and snippets.

@samisnotinsane
Last active February 25, 2020 23:17
Show Gist options
  • Save samisnotinsane/69f6eaf3ca6bb5cb979e1dd73264ecd7 to your computer and use it in GitHub Desktop.
Save samisnotinsane/69f6eaf3ca6bb5cb979e1dd73264ecd7 to your computer and use it in GitHub Desktop.
An example click command line application with options, arguments and context.
import click
class Config(object):
def __init__(self):
self.verbose = False
pass_config = click.make_pass_decorator(Config, ensure=True)
@click.group()
@click.option('--verbose', is_flag=True)
@click.option('--home-directory', type=click.Path())
@pass_config
def cli(config, verbose, home_directory):
config.verbose = verbose
if home_directory is None:
home_directory = '.'
config.home_directory = home_directory
@cli.command()
@click.option('--string', default='World',
help='This is the thing that is greeted.')
@click.option('--repeat', default=1,
help='How many times you should be greeted.')
@click.argument('out', type=click.File('w'), default='-',
required=False)
@pass_config
def say(config, string, repeat, out):
"""
This script greets you.
:param OUT: This is the output location.
:return: The greeting.
"""
if config.verbose:
click.echo('We are in verbose mode')
click.echo('Home directory is {0}'.format(config.home_directory))
for x in range(repeat):
click.echo('Hello {0}'.format(string), file=out)
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment