How to create CLI in Python?

| |

Home » How to create CLI in Python?

A command-line interface is a powerful tool for developers and admins. This tool helps you to automate routine activities and provides easy access to the full power of a programming language. There are many different command-line interfaces but today, we will look at how to create CLI using Python and a library called click.

What is CLI?

Command-line interface (CLI) is a way of interacting with a computer program where the user types a command into a text terminal. A program that requires the user to type in commands is often referred to as a command-line interface, command language, or terminal interface. For example, the Python interpreter can be called using the command python. Operating systems may also have a command-line interface for use in controlling certain functions, such as disk imaging with the dd command in Unix-like operating systems. In Python, a program can be accessed via the command line by creating a Python script, called a CLI (command-line interface).

Prerequisites:

Create a virtual environment:

To create the virtual environment use the following command in your terminal or command prompt

mkdir cli
cd cli

Create a virtual environment

python3 -m venv cli

Activate the environment in windows

cli\Scripts\activate.bat

Activate the environment in Linux

source cli/bin/activate

Click:

Click is a Python package for letting apps have unique, tailored interfaces that are constructed in an organized, composable way. It lets developers configure and extend the interface with minimal effort and provides sensible defaults that enable rapid configuration.

It aims to make the process of writing command-line tools quick and fun, as well as flexible so that you can prevent any frustration coming from not being able to implement an intended CLI API.

You can install click by using the following command in your terminal.

pip install click

Example -1:

What we are making this CLI do is if someone types their name while running the script it will say in return hello and then the name of the user. You will understand it more if you look at the output.

import click

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

if __name__ == "__main__":
    main()

Code explanation:

  1. Import click library.
  2. Attach the decorator to the main function. And develop our example by parameterizing the name using a click decorator click.command.
  3. Adding the second decorator click.argument to specify the name of the variable that’s going to contain the argument that we are going to pass in.

Output:

As you can see that our first small cli works perfectly now we are going to add some more functions to this cli.

import click

@click.command()
@click.argument("name")
@click.option('--number', type=int)
def main(name, number):
    for i in range(number):
        print(f'Hello {name}')

if __name__ == "__main__":
    main()

This example is more or less similar to the previous one but here we added one more decorator click.option also specifies the data type and then we add it in the for loop so it can return it multiple times in the output.

Output

As you can see that now we can give an option in the command line and enhance our functionality.

One of the interesting about the click is that it allows you to incorporate progressive help massage. if we put ourselves in the place of the end-user we can ask ourselves if they are familiar with the script or know much about coding. So what they can do let me show you.

The user can use the –help parameter then it will generate dynamic output. Out of the box, click try to provide some sort of assistance on what you can do with the script.

As you can see in the output that click gives you some additional uses tips of the script it also gives you the options. Remember this output is generated dynamically so if your script is different than this then the output will also be different.

You can also add the help message in the script so that the end-user can better understand the cli.

import click

@click.command()
@click.argument('name')
@click.option('--number', type=int, help="please enter the number of time you want to show the message")
def main(name, number):
    '''
    write your help message here
    '''
    for i in range(number):
        print(f'Hello {name}')

if __name__ == "__main__":
    main()

Output

As you can see how the end-user will know exactly what they have to enter to use the cli.

Example -2:

In this example, we will create a cli so that the user can only enter specific values.

import click

@click.command()
@click.option('--weather', type=click.Choice(['sunny', 'rainy', 'snowy']), help="Please select the weather type")
def main(weather):
    print(f'My fav weather is {weather}')

if __name__ == "__main__":
    main()

The code is very straightforward forward what we did here is simply used click.option decorator that is available is clicked library and the rest is the same as the previous example.

Output:

Example 3: Create a CLI with a group of commands

This is an example of a restaurant where users want to order lunch or dinner and whether they prefer pizza over burgers. you will better understand this by looking at the output.

import click

# creating group
@click.group()
def cli():
    pass

# creating subgroup for lunch
@cli.group()
def lunch():
    pass

# creating subgroup for dinner
@cli.group()
def dinner():
    pass

@click.command()
def burger():
    print(f'Enjoy your meal!')

@click.command()
def pizza():
    print(f'Enjoy your meal!')

lunch.add_command(burger)
dinner.add_command(burger)
lunch.add_command(pizza)
dinner.add_command(pizza)


if __name__ == "__main__":
    cli()

Here we are creating a group of commands for the end-user to use and click.group parameter.

Output:

As you can see now the user has an option to select the dinner or lunch and then what dish you want to order.

Here’s a trick to make your command line more interesting-looking. We will be using here a Python library called color that you can install using the following command.

pip install color

Now import the library in your code like this 

from colorama import Fore, Back, Style

Then define the color in the print statement like this 

print(Fore.GREEN + f'Enjoy your meal!')

And that is it! You’re now generating console output in color as you defined. It’s simple and quick to generate but adds your prompt more character and personality than plain old boring black and white text.

Final Words

In this blog post, we learned how to create CLI using python and the click library. CLIs can come in handy in several different situations, and we explained some different situations here by giving you examples. We also used the colors library to add some color to the output.

Spread the love
 
   
Previous

Automate Reddit Posts using Python

Programmatically Generate Video or Animated GIF in Python

Next

Leave a Comment