Develop Python Command Line (CLI) Application With Click

December 22, 2018

Install click

pip install click

Why? Personally I like declaring command and parameters using decorators/annotations.

NOTE: Alternatives include argparse (native python support), Docopt, Clint, etc.

A sample click cli application which support 2 commands, with required and optional parameters.

import click

@click.group()
def cli():
    pass

@cli.command()
@click.option('--name', required=True)
# @click.option('--name', prompt='Your name', help='The person to greet.')
# @click.argument('name')
@click.option('--count', type=int, default=1, help='Number of greetings.')
def hello(name, count):
    click.echo('Hello {}, No {}'.format(name, count))


@cli.command()
def test():
    click.echo('test')

# cli.add_command(hello)
# cli.add_command(test)

if __name__ == '__main__':
    cli()

Sample usage

python app.py test
python app.py hello --name Desmond
python app.py hello --name Desmond --count 9
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.