Python Click Module
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the "Command Line Interface Creation Kit".
Installation
pip install click
Basic Usage
Click uses decorators to bind functions to command line commands.
import click
@click.command()
def hello():
click.echo('Hello World!')
if __name__ == '__main__':
hello()
Adding Options
You can add options using @click.option.
import click
@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):
for _ in range(count):
click.echo(f"Hello {name}!")
if __name__ == '__main__':
hello()
Run: python script.py --count=3 (it will prompt for name).
Arguments
Arguments are positional parameters.
@click.command()
@click.argument('filename')
def touch(filename):
click.echo(f"Touching {filename}")
Grouping Commands
You can group multiple commands under a single entry point.
import click
@click.group()
def cli():
pass
@cli.command()
def initdb():
click.echo('Initialized the database')
@cli.command()
def dropdb():
click.echo('Dropped the database')
if __name__ == '__main__':
cli()
Run: python script.py initdb