DEV Community

jlsai
jlsai

Posted on

Elevating CLI with Powerful Libraries

Command Line Interfaces have been a fundamental component of computer systems for decades, providing a text-based means to interact with software and accomplish various tasks. Although traditional CLIs serve their purpose well, the introduction of powerful libraries has transformed these interfaces into highly versatile and user-friendly tools.

CLIs were not always user-friendly. They often demanded users to memorize complex commands and navigate through extensive help documentation. This is where libraries come into play, making CLIs more accessible and powerful for both developers and end-users.

  1. Click (Python):
import click

@click.command()
@click.option('--name', prompt='Your name', help='The name to greet.')
@click.option('--greeting', default='Hello', help='The greeting message.')
def greet(name, greeting):
    """Greet a user with a customized message."""
    click.echo(f'{greeting}, {name}!')

if __name__ == '__main__':
    greet()
Enter fullscreen mode Exit fullscreen mode
python script.py
Your name: Bob
Hello, Bob!
Enter fullscreen mode Exit fullscreen mode

a Python script that converts files between different formats. Using Click, you can create a user-friendly CLI with a single command:

    import click

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

@cli.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def change_password(password):
    click.echo(f'Password changed to: {password}')

@cli.command()
@click.option('--username', prompt=True)
@click.password_option()
def create_user(username, password):
    click.echo(f'User {username} created with password: {password}')

if __name__ == '__main__':
    cli()
Enter fullscreen mode Exit fullscreen mode

This straightforward CLI is easy to understand and can be extended with additional options and features.

  1. Inquirer:

    Inquirer lets you create an interactive CLI to gather information. It provides a set of prompts and input utilities to facilitate user interaction by displaying questions, choices, and input fields in the terminal.

    def options():
    
    options = [
        inquirer.List('option',
                      message="What will it be?",
                      choices=['option 1', 'option 2', 'option 3'])
    ]
    

Image description

This library simplifies the process of gathering user preferences through a user-friendly interface.

  1. Argparse (Python): argparse is a Python standard library module that provides a convenient way to parse command-line arguments and options. argparse simplifies the process of interacting with a script from the command line by handling the parsing and validation of input arguments.

Imagine you're developing a Python script that needs to accept command-line arguments. Argparse simplifies the process:

import argparse

def add_numbers():
    parser = argparse.ArgumentParser(description='Add two numbers.')

    parser.add_argument('num1', type=int, help='First number to add')
    parser.add_argument('num2', type=int, help='Second number to add')

    args = parser.parse_args()

    result = args.num1 + args.num2
    print(f'The result of {args.num1} + {args.num2} is {result}')

if __name__ == '__main__':
    add_numbers()
Enter fullscreen mode Exit fullscreen mode
python script.py 5 7

The result of 5 + 7 is 12
Enter fullscreen mode Exit fullscreen mode

Argparse automatically generates helpful usage information and handles argument parsing.

  1. Curses (Python):

    Example: The "curses" library in Python provides a way to create interactive terminal applications. Here's a simple example of a text-based calculator:

    import curses
    
    def main(stdscr):
        # Set up the screen
        curses.curs_set(0)
        stdscr.clear()
        stdscr.refresh()
    
        # Main loop
        while True:
            stdscr.addstr(0, 0, "Enter an expression (q to quit): ")
            stdscr.refresh()
            expression = stdscr.getstr(1, 0).decode('utf-8')
    
            if expression == 'q':
                break
    
            try:
                result = eval(expression)
                stdscr.addstr(2, 0, f"Result: {result}")
            except Exception as e:
                stdscr.addstr(2, 0, f"Error: {str(e)}")
    
            stdscr.refresh()
    
    if __name__ == "__main__":
        curses.wrapper(main)
    

Image description

The "curses" library enables the creation of interactive, text-based applications with features like input fields, menus, and more.

Libraries have revolutionized the way we interact with command-line interfaces, making them more accessible, versatile, and potent. Whether you're a developer building CLI tools or an end-user navigating these interfaces, these libraries have significantly improved the overall experience. Don't hesitate to explore these libraries and elevate your command-line experience.

Top comments (0)