Create a cli with click and python

First what is a CLI : a cli or command line interface is a man-machine interface in which the communication between the user and the computer is done in text mode.

Install Click #

Direct installation

$ pip3 install click

With requirements.txt.

requirements.txt

click
$ pip3 install -r requirements.txt

Create your first cli command #

To use a cli command you need to import click & create a function that represent your command.

hello.py

import click

@click.command()
def hello():
  click.echo("Hello World")

if __name__ == "__main__":
  hello()

If we launch this command, it should show us Hello World in the console.

$ python3 hello.py
Hello World

We can pass options to our cli #

To use a options we need to use @click.option

With one option #

hello.py

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
def hello(count):
  for x in range(count):
    click.echo(f"{count}: Hello World")

if __name__ == "__main__":
  hello()

The output will be :

$ python3 hello.py --count=3
0: Hello World
1: Hello World
2: Hello World

With multiple options #

hello.py

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', default="Ewen", help='Your name.')
def hello(count, name):
  for x in range(count):
    click.echo(f"{count}: Hello {name}!")

if __name__ == "__main__":
  hello()

The output will be :

$ python3 hello.py --count=3
0: Hello Ewen
1: Hello Ewen
2: Hello Ewen

With another name :

$ python3 hello.py --count=3 --name=Roman
0: Hello Roman
1: Hello Roman
2: Hello Roman

We can pass parameters to our cli #

To use a parameres we need to use @click.parameter

With one parameter #

hello.py

import click

@click.command()
@click.argument('name')
def hello(name):
  click.echo(f"Hello {name}")

if __name__ == "__main__":
  hello()
$ python3 hello.py Roman
Hello Roman

With one parameter and one option. #

hello.py

import click

@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(f"Hello {name}")

if __name__ == "__main__":
  hello()
$ python3 hello.py Roman --count=3
Hello Roman
Hello Roman
Hello Roman