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.
Direct installation
$ pip3 install click
With requirements.txt.
requirements.txt
click
$ pip3 install -r requirements.txt
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
To use a options we need to use @click.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
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
To use a parameres we need to use @click.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
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