DEV Community

SK RAJIBUL
SK RAJIBUL

Posted on

Command-line interfaces (CLI) in Python using Typer!

💡 With Typer, you can:

✅ Define commands and parameters effortlessly.
✅ Provide clear documentation for each command.
✅ Accept named arguments for flexible input.

🔍 Typer vs. argparse:

1️⃣ Simple Syntax: Typer streamlines with concise code.

2️⃣ Auto Type Conversion: Typer handles data types automatically.

3️⃣ Automatic Docs: Typer auto-generates help text from docstrings.

📌 Check out this code example demonstrating Typer's features:

import typer

app = typer.Typer()

@app.command()
def greet(name: str):
 """
 Greet a person by name.
 """
 typer.echo(f"Hello, {name}!")

@app.command()
def calculate(x: int, y: int, operation: str = "add"):
 """
 Perform a calculation.
 """
 result = None
 if operation == "add":
 result = x + y
 elif operation == "subtract":
 result = x - y
 elif operation == "multiply":
 result = x * y
 elif operation == "divide":
 result = x / y
 else:
 typer.echo("Invalid operation. Available operations are: add, subtract, multiply, divide.")
 raise typer.Abort()

 typer.echo(f"Result of {operation}: {result}")

if __name__ == "__main__":
 app()
Enter fullscreen mode Exit fullscreen mode

🚢 Additionally, Typer is extremely helpful for creating Docker CLI applications.

🔧 In my recent project, I containerized my CLI app to perform multiple tasks using the same image. This approach simplified deployment and management, as I didn't need to handle multiple images for each task.

To use different Typer commands as the entry point (CMD) for your Docker container, you can pass the command name as an argument when running the container.

Here's how you can achieve this:

# Use the official Python 3.9 slim image as the base
FROM python:3.9-slim

# Set the working directory inside the container
WORKDIR /app

# Copy the Python script into the container
COPY script.py .

# Install Typer library
RUN pip install typer

# Define the entry point as the Python script with command-line arguments
ENTRYPOINT ["python", "script.py"]
Enter fullscreen mode Exit fullscreen mode

With this setup, you can run different Typer commands by passing the command name as an argument when running the Docker container:

docker run -it --rm my_image_name greet --name John
Enter fullscreen mode Exit fullscreen mode
docker run -it --rm my_image_name calculate --x 10 --y 5 --operation subtract
Enter fullscreen mode Exit fullscreen mode

Top comments (0)