Last modified: Nov 02, 2025 By Alexander Williams
Python Typer Colored Terminal Output Guide
Python Typer makes CLI development simple. It also offers great terminal styling. This guide shows how to add colors to your output.
Why Style Terminal Output?
Colored output improves user experience. It makes important information stand out. Errors in red catch attention. Success messages in green feel positive.
Styled text guides users through your application. It makes your CLI tools look professional. Good visual hierarchy helps users understand output faster.
Basic ANSI Color Codes
Terminals understand ANSI escape codes. These codes control text formatting. Typer's echo function supports these codes natively.
import typer
app = typer.Typer()
@app.command()
def hello():
# Red text
typer.echo("\033[91mHello World!\033[0m")
# Green text
typer.echo("\033[92mSuccess message\033[0m")
# Yellow text
typer.echo("\033[93mWarning message\033[0m")
if __name__ == "__main__":
app()
$ python app.py hello
Hello World! # Appears in red
Success message # Appears in green
Warning message # Appears in yellow
Using Typer's Built-in Colors
Typer provides a better way than raw ANSI codes. The secho function handles colors automatically. It's cleaner and more readable.
import typer
app = typer.Typer()
@app.command()
def show_colors():
typer.secho("Error message", fg=typer.colors.RED, bold=True)
typer.secho("Success!", fg=typer.colors.GREEN)
typer.secho("Warning", fg=typer.colors.YELLOW)
typer.secho("Info text", fg=typer.colors.BLUE)
if __name__ == "__main__":
app()
The secho function is the recommended approach. It automatically handles reset codes. This prevents color bleeding into subsequent output.
Available Colors and Styles
Typer supports many colors and styles. You can combine them for better effects. Here are the main options available.
import typer
@app.command()
def all_styles():
# Basic colors
typer.secho("Red text", fg=typer.colors.RED)
typer.secho("Green text", fg=typer.colors.GREEN)
typer.secho("Blue text", fg=typer.colors.BLUE)
# Bright colors
typer.secho("Bright red", fg=typer.colors.BRIGHT_RED)
typer.secho("Bright green", fg=typer.colors.BRIGHT_GREEN)
# Text styles
typer.secho("Bold text", bold=True)
typer.secho("Underlined", underline=True)
Background Colors
You can also set background colors. This creates highlighted text effects. Combine with foreground colors for contrast.
@app.command()
def background_demo():
# White text on red background
typer.secho("ALERT!", fg=typer.colors.WHITE, bg=typer.colors.RED)
# Black text on yellow background
typer.secho("Warning", fg=typer.colors.BLACK, bg=typer.colors.YELLOW)
# Custom combination
typer.secho("Important", fg=typer.colors.CYAN, bg=typer.colors.MAGENTA)
Practical Use Cases
Let's see real-world examples. These patterns work well in production applications.
@app.command()
def file_processor(filename: str):
try:
# Process file
typer.secho(f"Processing {filename}...", fg=typer.colors.BLUE)
# Simulate work
import time
time.sleep(1)
# Success message
typer.secho("File processed successfully!", fg=typer.colors.GREEN)
except FileNotFoundError:
# Error handling with color
typer.secho(f"Error: File {filename} not found!",
fg=typer.colors.RED, bold=True)
Progress Indicators with Color
Combine colors with progress bars. This creates engaging user interfaces. Users appreciate visual feedback.
@app.command()
def long_process():
import time
typer.secho("Starting process...", fg=typer.colors.BLUE)
with typer.progressbar(range(100)) as progress:
for i in progress:
time.sleep(0.02) # Simulate work
typer.secho("Process completed!", fg=typer.colors.GREEN, bold=True)
Rich Integration for Advanced Styling
For complex styling, use Rich with Typer. The Python Typer Rich Integration Guide covers this in depth. Rich offers tables, panels, and more.
import typer
from rich.console import Console
from rich.table import Table
app = typer.Typer()
console = Console()
@app.command()
def rich_demo():
table = Table(title="User Data")
table.add_column("Name", style="cyan")
table.add_column("Age", style="magenta")
table.add_row("Alice", "25")
table.add_row("Bob", "30")
console.print(table)
Color Configuration and Themes
Create consistent color schemes. Define color constants for maintainability. This ensures visual consistency across your application.
# Color theme configuration
class Colors:
ERROR = typer.colors.RED
SUCCESS = typer.colors.GREEN
WARNING = typer.colors.YELLOW
INFO = typer.colors.BLUE
@app.command()
def themed_output():
typer.secho("Database connected", fg=Colors.SUCCESS)
typer.secho("Cache miss detected", fg=Colors.WARNING)
typer.secho("Starting server...", fg=Colors.INFO)
Handling Color Support Detection
Not all terminals support colors. Your application should handle this gracefully. Check color support before applying styles.
def safe_secho(message, **kwargs):
"""Safely output colored text, falling back to plain text if needed"""
try:
typer.secho(message, **kwargs)
except (OSError, IOError):
# Fallback to plain text if color not supported
typer.echo(message)
@app.command()
def safe_colors():
safe_secho("This works everywhere", fg=typer.colors.GREEN)
Integration with Other Typer Features
Colored output works well with other Typer features. Combine with global options for consistent theming. Use with async commands for modern applications.
Best Practices
Use colors sparingly and consistently. Don't overuse bright colors. Establish a clear color hierarchy in your application.
Test your colors in different terminals. Ensure good contrast for readability. Consider color-blind users in your design choices.
Document your color scheme. This helps maintain consistency as your application grows. Team members will understand the visual language.
Conclusion
Colored terminal output enhances CLI applications significantly. Typer makes implementation straightforward with secho and ANSI code support.
Start with basic colors for errors and success messages. Progress to advanced Rich integration for complex interfaces. Always consider terminal compatibility and accessibility.
Well-designed color schemes make your tools more professional and user-friendly. They guide users through workflows and highlight important information effectively.