Building Command Line Application with Click

Virtualenv is recommended to creste command line application with “click”. To start with this, lets create a program disp.py which displays some messages.

def cli():

print(“Hello World”)

Next we are creating a setup.py because this will help us to use the python module.

from setuptools import setup

setup(

name=”Display”,

version=’0.1′,

py_modules=[‘hello’],

install_requires=[‘Click’,],

entry_points=”’ [console_scripts] Display=disp:cli ”’,

)

We have mentioned the starting point of the tool in the entry_points. We can install the virtualenv which makes it easier and activate it.

$python3 -m pip install –editable

$Display

Hello world

–help will show the options of the setup file.

Instead of using the standard print function, we can use echo which is available in the click module.

click.echo(“Hello world”)

Boolean flags

In case if a option is provided, then it will print the extra message else it will do some other task. In python, we will call the flag as verbose

import click

@click.command()

@click.option(‘–verbose’, is_flag=True, help=”the message in the verbose will be displayed”)

def cli(verbose):

if(verbose):

click.echo(“Verbose message”)

Similarly we can use multiple options for the verbose method.

Password Confirmation

There is a super fast way for the password confirmation which can be used. This method is imported from the Click module. If the password is right, it displays the content else it displays the error message.

@click.password_option()

Arguement

These arguements are must be provided that is,there is no default value. The arguements are Strings by default.

@click.arguement( ‘name’)

Leave a comment