Python Click - Creating Command Line Interfaces
Python Click - Creating Command Line Interfaces
Python click
last modified July 6, 2020
Python click tutorial shows how to create command line interfaces with the click module.
Python click
Python click module is used to create command-line (CLI) applications. It is an easy-to-use
alternative to the standard optparse and argparse modules. It allows arbitrary nesting of
commands, automatic help page generation, and supports lazy loading of subcommands at
runtime.
The click module was created as a supporting library for the Flask web framework.
The commands are basic building blocks of an application. Click defines commands through
decorators. They are created with the click.command() decorator. Values are passed to the
commands via options or arguments. Options are added with the click.option() decorator,
arguments with the click.argument(). Values in options follow the name of the option while
arguments are taken positionally.
$ pip install -U click
We install the click module. For coloured output, we also need the colorama module.
simple.py
import click
@click.command()
def hello():
click.echo('Hello there')
if __name__ == '__main__':
hello()
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
@click.command()
def hello():
click.echo('Hello there')
Click uses the echo instead of the print. It increases compatibility and adds colouring support.
$ ./simple.py
Hello there
$ ./simple.py --help
Usage: simple.py [OPTIONS]
Options:
--help Show this message and exit.
argument.py
#!/usr/bin/python3
import click
@click.command()
@click.argument('name', default='guest')
def hello(name):
click.echo(f'Hello {name}')
if __name__ == '__main__':
hello()
The example builds a message with the given argument value. If there is no argument, the default
guest is used. The argument is passed to the function as a variable.
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
$ ./argument.py Peter
Hello Peter
$ ./argument.py
Hello guest
argument_type.py
#!/usr/bin/python3
import click
@click.command()
@click.argument('name', default='guest')
@click.argument('age', type=int)
def hello(name, age):
click.echo(f'{name} is {age} years old')
if __name__ == '__main__':
hello()
In the example, we have two arguments: name and age. They are generated positionally, the first is
name, the second is age.
$ ./argument_type.py Peter 34
Peter is 34 years old
variable_args.py
#!/usr/bin/python3
import click
from operator import mul
from functools import reduce
@click.command()
@click.argument('vals', type=int, nargs=-1)
def process(vals):
The example creates a process command, which may take variable number of integer values in the
vals argument. The command calculates the sum and the product of the values.
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
$ ./variable_args.py 1 2 3 4 5
The sum is 15
The product is 120
dots.py
#!/usr/bin/python3
import click
@click.command()
@click.option('--n', type=int, default=1)
def dots(n):
click.echo('.' * n)
if __name__ == '__main__':
dots()
In the example, we have the --n option which takes a number. The number determines how many
times the dot is printed to the console.
$ ./dots.py --n 17
.................
option_names.py
#!/usr/bin/python3
import click
@click.command()
@click.option('-s', '--string')
def output(string):
click.echo(string)
if __name__ == '__main__':
output()
In the example, we create an option with both short and long names. The name of the variable
passed to the function is string, derived from the longer option name.
$ ./option_names.py -s sky
sky
$ ./option_names.py --string cloud
cloud
prompt.py
#!/usr/bin/python3
import click
@click.command()
@click.option("--name", prompt="Your name", help="Provide your name")
def hello(name):
click.echo(f"Hello, {name}")
if __name__ == '__main__':
hello()
$ ./prompt.py
Your name: Peter
Hello, Peter
coloured.py
#!/usr/bin/python3
import click
@click.command()
def coloured():
click.secho('Hello there', fg="blue", bold=True)
if __name__ == '__main__':
coloured()
The example outputs the text in bold blue colour.
flags.py
#!/usr/bin/python3
import click
@click.command()
@click.option('--blue', is_flag=True, help='message in blue color')
def hello(blue):
if blue:
click.secho('Hello there', fg='blue')
else:
click.secho('Hello there')
if __name__ == '__main__':
hello()
In the example, we define a --blue boolean option with the is_flag parameter. If set, it prints the
message in blue colour.
flags2.py
#!/usr/bin/python3
import click
@click.command()
@click.argument('word')
@click.option('--shout/--no-shout', default=False)
def output(word, shout):
if shout:
click.echo(word.upper())
else:
click.echo(word)
if __name__ == '__main__':
output()
In the second case, we define --shout and --no-shout flags. If the --shout flag is set, the
specified argument is outputted in uppercase.
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
env_var.py
#!/usr/bin/python3
import click
import os
click.echo(os.listdir(mydir))
if __name__ == '__main__':
dolist()
The example prints the content of the directory specified in the MYDIR environment variable.
multi_val.py
#!/usr/bin/python3
import click
@click.command()
@click.option('--data', required=True, type=(str, int))
def output(data):
click.echo(f'name={data[0]} age={data[1]}')
if __name__ == '__main__':
output()
In the example, the --data option takes two values that become a Python tuple. The values are
used to build a message.
multiples.py
#!/usr/bin/python3
import click
@click.command()
@click.option('--word', '-w', multiple=True)
def words(word):
click.echo('\n'.join(word))
if __name__ == '__main__':
words()
In the example, we can specify the --word/-w options multiple times.
Google Ads -
Sitio O cial
Con Google Ads, no hay
contratos ni mínimo de
Google Ads inversión.
words.txt
sky
cloud
water
forest
rock
moon
falcon
lake
head.py
#!/usr/bin/python3
import click
@click.command()
@click.argument('file_name', type=click.File('r'))
@click.argument('lines', default=-1, type=int)
def head(file_name, lines):
counter = 0
print(line.strip())
counter += 1
if counter == lines:
break
if __name__ == '__main__':
head()
$ ./head.py words.txt 4
sky
cloud
water
forest
head2.py
#!/usr/bin/python3
import click
@click.command()
@click.argument('file_name', type=click.Path(exists=True))
@click.argument('lines', default=-1, type=int)
def head(file_name, lines):
counter = 0
print(line.strip())
counter += 1
if counter == lines:
break
if __name__ == '__main__':
head()
import click
@click.group()
def messages():
pass
@click.command()
def generic():
click.echo('Hello there')
@click.command()
def welcome():
click.echo('Welcome')
messages.add_command(generic)
messages.add_command(welcome)
if __name__ == '__main__':
messages()
$ ./groups.py --help
Usage: groups.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
generic
welcome
The help message shows two commands.
groups2.py
#!/usr/bin/python3
import click
@click.group()
def cli():
pass
@cli.command(name='gen')
def generic():
click.echo('Hello there')
@cli.command(name='wel')
def welcome():
click.echo('Welcome')
if __name__ == '__main__':
cli()
This is an alternative syntax for creating a command group. The commands take the name of the
function but can be given another name with the name option.
$ ./groups2.py gen
Hello there
$ ./groups2.py wel
Welcome