Creating CLI Applications

Loading

A Command Line Interface (CLI) application allows users to interact with programs through a terminal or command prompt instead of a graphical interface. Python is one of the best languages for building CLI applications due to its simplicity and powerful libraries.


1. Why Build CLI Applications?

Lightweight & Fast – No need for a GUI, making it efficient.
Automated Workflows – Easily script tasks for automation.
Remote Accessibility – Run programs on servers without a GUI.
Flexible Input Handling – Accepts command-line arguments, interactive input, or configuration files.


2. Basic CLI Application Using sys.argv

The sys module allows handling command-line arguments.

Example: Simple CLI Tool

import sys

def greet():
if len(sys.argv) > 1:
name = sys.argv[1]
print(f"Hello, {name}!")
else:
print("Usage: python script.py <name>")

greet()

How to Run

python script.py Alice

Output:

Hello, Alice!

sys.argv[0] is always the script name.
sys.argv[1] is the first argument passed.


3. Using argparse for Advanced CLI Arguments

The argparse module makes handling command-line arguments more user-friendly.

Example: CLI with Named Arguments

import argparse

def main():
parser = argparse.ArgumentParser(description="A simple CLI calculator.")
parser.add_argument("num1", type=float, help="First number")
parser.add_argument("num2", type=float, help="Second number")
parser.add_argument("--operation", choices=["add", "sub", "mul", "div"], default="add", help="Operation to perform")

args = parser.parse_args()

if args.operation == "add":
result = args.num1 + args.num2
elif args.operation == "sub":
result = args.num1 - args.num2
elif args.operation == "mul":
result = args.num1 * args.num2
elif args.operation == "div":
result = args.num1 / args.num2

print(f"Result: {result}")

if __name__ == "__main__":
main()

How to Run

python calculator.py 10 5 --operation mul

Output:

Result: 50.0

Improves error handling
Supports optional arguments
Automatically generates --help documentation


4. Interactive CLI Applications with input()

For CLI apps requiring user input, use input().

Example: Interactive To-Do List

def todo_list():
tasks = []
while True:
task = input("Enter a task (or type 'exit' to quit): ")
if task.lower() == "exit":
break
tasks.append(task)

print("\nYour To-Do List:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")

todo_list()

How to Run

python todo.py

Handles multiple inputs
Stores and displays user tasks


5. Building a CLI App with click

The click library simplifies CLI development and supports subcommands.

Installation

pip install click

Example: CLI with Click

import click

@click.command()
@click.argument("name")
@click.option("--greeting", default="Hello", help="Custom greeting message.")
def greet(name, greeting):
"""A simple CLI greeting app."""
click.echo(f"{greeting}, {name}!")

if __name__ == "__main__":
greet()

How to Run

python greet.py Alice --greeting "Hi"

Output:

Hi, Alice!

Easy to define commands and options
Handles input validation


6. Packaging CLI Applications as Executables

To distribute your CLI application without requiring Python installation, use PyInstaller.

Installation

pip install pyinstaller

Creating an Executable

pyinstaller --onefile my_cli_app.py

Generates a single-file executable in the dist/ folder.

Leave a Reply

Your email address will not be published. Required fields are marked *