How To Make Beautiful Command-Line Interfaces In Python?


In this article, we will learn and explore how we can create beautiful command line interfaces in Python.

First, let's talk a little about Python and then we will talk about command line interfaces.

Why Python?

Python is a popular high−level programming language known for its simplicity, readability, and versatility. Created in the late 1980s by Guido van Rossum, Python has since become one of the most widely used languages for web development, scientific computing, data analysis, and machine learning.

Python's syntax is designed to be intuitive and easy to understand, with a focus on reducing the amount of code needed to express a given task. This makes it a popular choice for beginners, as well as experienced programmers who want to quickly prototype or develop complex applications.

Python is a popular choice for building command−line interfaces (CLIs) because it is a high−level language with a clean and readable syntax that makes it easy to write and maintain code. Python's extensive standard library includes modules that support building CLIs, such as argparse, click, and docopt, which provide easy−to−use and flexible command−line argument parsing and help message generation.

Moreover, Python is platform−independent, meaning that code written on one platform can easily be run on another platform without any modification. This makes it easier for developers to write cross−platform command−line applications that can be used on multiple operating systems, including Windows, Linux, and macOS.

Python also has a large and active community, which means that developers can easily find help, resources, and third−party packages to extend the functionality of their CLI applications. Additionally, Python is highly extensible, which means that developers can write Python modules in C or C++ to optimise performance−critical parts of their CLI applications.

Overall, Python's ease of use, readability, cross−platform compatibility, and extensive libraries make it a great choice for building command−line interfaces.

Now let's talk a little bit more about command line interfaces.

Using a CLI in Python typically involves defining a main function that is called when the program is run from the command line. The argparse module provides a way to define the command line arguments and options that the user can enter, and parse them into a set of Python objects that can be used within the main function.

The click library provides a higher−level interface for building CLIs in Python, with a more intuitive syntax and support for features such as command groups, context objects, and progress bars. docopt is another popular library for building CLIs, which uses a syntax that is similar to writing usage examples in a README file.

In addition to building CLIs, Python can also be used to automate tasks on the command line using the subprocess module, which allows developers to run external commands and interact with their output within a Python program. This can be useful for tasks such as file manipulation, system administration, and testing.

Now that we have explored in detail about the different packages available to us for creating CLI's, let's make use of them in code one by one.

argparse

argparse is a Python module for parsing command−line arguments and generating help messages. It provides an easy way to define and handle command−line arguments in a Python program. With argparse, developers can specify the arguments that their program expects, and argparse takes care of parsing the command−line arguments provided by the user.

argparse provides a number of features, such as positional arguments, optional arguments, default values, type checking, help messages, and sub−commands. It also supports different argument styles, including short options (e.g., "-f"), long options (e.g., "--file"), and combined short options (e.g., "-xyz").

Consider the code shown below.

Example

# argparse example

import argparse

def main():
	parser = argparse.ArgumentParser(description='Add some integers.')
	parser.add_argument('integers', metavar='N', type=int, nargs='+', help='integer list')
	parser.add_argument('--sum', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
	args = parser.parse_args()
	result = args.sum(args.integers)
	print(result)

if __name__ == '__main__':
	main()

Explanation

This code lets you run a Python script with some extra information you provide when you run it.

First, you need to specify what information you want to add. You can add integers and choose whether to sum them or find the maximum. You do this by setting up arguments with the argparse module.

Next, when you run the program, you can pass in the values for the arguments. The program will read these values and use them to do the calculation you requested.

Finally, the program prints the result of the calculation to the screen.

The if __name__ == '__main__': part just makes sure that the program runs the main() function when you run it, but doesn't run it if you import the code into another program.

To run the above python script, we can run the command shown below.

Command

python3 main.py 1 2 3 4  

When we pass multiple numbers as arguments to our command line interface, we will get the following output.

Output

4

Now let's pass another argument, named --sum along with the numbers.

Command

python3 main.py 1 2 3 4  --sum

Output

10

Click

Click is a Python library that makes it easy to create command line interfaces (CLIs) for your Python programs. It provides a simple and intuitive way to define command line arguments and options, and makes it easy to build complex command line interfaces with nested commands, help text, and more. With Click, you can create a professional−grade CLI for your Python program without having to write a lot of code. Many Python developers use Click to build CLIs for their programs.

Now let's first create a simple CLI using click, and the first requirement is to have click installed on our machine.

In order to install click, we can run the command shown below.

Command

pip install click

You can also use pip3, if you are on the latest version of python.

Consider the code shown below.

Example

# Click Example

import click

@click.command()
def main():
	click.echo("This is a CLI built with Click ✨")

if __name__ == "__main__":
	main()

Explanation

This code is an example of how to create a simple command line interface (CLI) for a Python program using the Click library.

The @click.command() decorator tells Click that the main function is a CLI command. When the program is run, Click will parse the command line arguments and call the appropriate CLI command.

The click.echo() function prints the specified text to the command line. In this case, it prints the message "This is a CLI built with Click".

The if __name__ == "__main__": block ensures that the main function is only called when the program is run directly, and not when it is imported as a module in another Python program.

When the program is run, the main function is called, which in turn calls the click.echo() function to print the message to the command line.

To run the above code we can run the command shown below.

Command

python3 main.py

Output

This is a CLI built with Click ✨

Now let's create an interactive CLI using click.

Consider the code shown below.

Example

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--verbose', is_flag=True, help='Print verbose output.')
def hello(name, count, verbose):
	"""Simple program that greets NAME for a total of COUNT times."""
	for i in range(count):
    	greeting = f'Hello, {name}!'
    	if verbose:
        	greeting += f' ({i+1}/{count})'
    	click.echo(greeting)

if __name__ == '__main__':
	hello()

Explanation

This code defines a CLI command called hello using the Click library. The @click.command() decorator tells Click that hello is a command.

The @click.option() decorators define three options that can be passed to the hello command. --name specifies the name of the person to greet, --count specifies the number of times to greet them, and --verbose is a flag that enables verbose output.

To run the above code we can run the command shown below.

Command

python3 main.py --name TutorialsPoint --count 3 --verbose

Output

Hello, TutorialsPoint! (1/3)
Hello, TutorialsPoint! (2/3)
Hello, TutorialsPoint! (3/3)

Now let's make one more creative CLI by making use of docopt.

Docopt

Docopt is a Python library for creating command−line interfaces by parsing the arguments passed to a Python script. Unlike argparse or click, which require explicit definition of commands and arguments, docopt uses a natural language syntax to specify command−line arguments and their usage in the program. This makes it easy to define and use command−line interfaces without having to write a lot of boilerplate code. With docopt, you can define your program's usage documentation in a human−readable format, and then docopt will automatically generate the command−line parser for you.

Consider the code shown below.

Example

# docopt example

#!/usr/bin/env python

from docopt import docopt

def main(args):
	if args['--version']:
    	print('My CLI Tool Version 1.0')
	elif args['hello']:
    	print(f'Hello, {args["<name>"]}!')
	elif args['goodbye']:
    	print(f'Goodbye, {args["<name>"]}!')
	else:
    	print(__doc__)

if __name__ == '__main__':
	args = docopt(__doc__, version='My CLI Tool Version 1.0')
	main(args)

Explanation

The docopt library is used to parse the command−line arguments based on the usage description specified in the script's docstring. The args dictionary contains the parsed command−line arguments.

The main function is the entry point for the script. It checks the command−line arguments passed to the script and prints the corresponding message.

If the --version option is specified, the script prints the version number. If the hello option is specified, it prints a greeting message with the name provided as an argument. If the goodbye option is specified, it prints a goodbye message with the name provided as an argument. If none of these options are specified, it prints the usage information.

To run the above code we can run the command shown below.

Command

python3 main.py hello TutorialsPoint

Output

Hello, TutorialsPoint!

Conclusion

In conclusion, the command−line interface (CLI) is an essential part of modern software development. Python provides several libraries, including argparse, Click, and Docopt, to build command−line interfaces quickly and easily. Each of these libraries has its own strengths and weaknesses, and the choice of which one to use depends on the specific requirements of the project.

Argparse is a built−in module that provides a simple and powerful way to parse command−line arguments. Click is a third−party library that offers a clean and intuitive syntax and is particularly useful for building complex command−line interfaces. Docopt is a natural language parser that generates a command−line parser based on a usage description.

Regardless of which library is chosen, it is important to design the command−line interface with the user in mind. The interface should be clear and easy to use, and it should provide helpful feedback to the user. With the right design and the appropriate library, Python developers can create powerful and user−friendly command−line interfaces that make their software more accessible and useful.

Updated on: 03-Aug-2023

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements