Click module in Python

Click package in Python is used to create command-line (CLI) applications. It was created for the Flask Web Development as a supporting library. Here, we will discuss in detail about this package along with its various uses.

Python Click package

  • It is used in place of the standard optparse and argparse modules.
  • However, it is lazily composable and fully nested.
  • It has strong information for parameters and commands.
  • In addition, it gives information on user consistent error messages if something goes inappropriate.
  • To define commands decorators are used.  click.command() decorator function is used.
  • Moreover, options are added as a click.option() decorator. Arguments are added using click.argument().

Functionality:

Basic functionalities of CLI are:

  • An argument.
  • An optional parameter.
  • A flag that is used to enable and disable certain functions.

Firstly Installation:

pip install click

Simple Example:

import click
@click.command()
def codespeedy():
    click.echo("Code Speedy")
if __name__=="__main__":
    codespeedy()

Click uses echo instead of print.

Argument Passing:

@click.command()
@click.argument('name')
def clickexample():
    click.echo("Hello,{}".format(name))
if __name__=="__main__":
    clickexample()

>>> python filename.py CodeSpeedy

Output:

Hello CodeSpeedy

In this example, a build message is given with an argument.

Optional Arguments:

Optional parameters can be added in the form of flags.

@click.command()
@click.option('--string',default="CodeSpeedy",help="click example")
def clickexample(string):
    click.echo("Hello,{}".format(string))
if __name__=="__main__":
    clickexample()

>>> python filename.py

Output:

Hello CodeSpeedy

Help:

Above all, an important step is to provide documentation to the code to build a perfect CLI. Therefore, click provides a formatted help text. Docstring specified in the function is used.

@click.command()
@click.argument('codespeedy')
def clickexample(codespeedy):
    click.echo(Codespeedy)
    click.echo("This is a CLI")
if __name__=="__main__":
    clickexample()

Error Handling:

Error handling is an important part of CLI. Therefore, how your code handles the errors matter and is most important. Click module has ClickException function which is used to handle the exceptions occurring in the program.

Example of ClickException:

try:
   pass
except:
   raise click.ClickException("Exception Ocurrred")

It is an interesting module to work on with a wide range of features and functionality.

Also read: Create a Progressbar in Tkinter Python

Leave a Reply