Skip to main content

A simple, powerful and cross-platform Python library for adding colors to your terminal output with cross-platform support, especially optimized for Windows 10+ terminals.

Project description

🎨 make_colors

A simple, powerful and cross-platform Python library for adding colors to your terminal output with cross-platform support, especially optimized for Windows 10+ terminals.

Python Version Platform License

📋 Table of Contents

Example Usage

✨ Features

  • 🖥️ Cross-platform support - Works on Windows, Linux, and macOS
  • 🎯 Windows 10+ optimized - Special support for modern Windows terminals
  • 🌈 Rich color palette - 16 colors with light variants
  • 📝 Simple syntax - Easy-to-use color shortcuts and full names
  • 🔧 Flexible formatting - Support for foreground/background combinations
  • 🚀 Lightweight - Minimal dependencies, fast performance
  • 🎛️ Environment control - Enable/disable colors via environment variables

📦 Installation

Install make_colors using pip:

pip install make_colors

🚀 Quick Start

from make_colors import make_colors

# Simple colored text
print(make_colors("Hello World!", "red"))

# Text with background
print(make_colors("Important Message", "white", "red"))

# Using shortcuts
print(make_colors("Quick and easy", "r", "bl"))  # red text, blue background

# Using underscore notation
print(make_colors("One-liner style", "green_yellow"))  # green text, yellow background

🎨 Color Reference

Available Colors

Color Name Shortcut Light Variant Light Shortcut
black b, bk lightblack lb
red r, rd, re lightred lr
green g, gr, ge lightgreen lg
yellow y, ye, yl lightyellow ly
blue bl lightblue lb
magenta m, mg, ma lightmagenta lm
cyan c, cy, cn lightcyan lc
white w, wh, wi, wt lightwhite lw

Color Preview

# Standard colors
print(make_colors("■ Black text", "black"))
print(make_colors("■ Red text", "red"))
print(make_colors("■ Green text", "green"))
print(make_colors("■ Yellow text", "yellow"))
print(make_colors("■ Blue text", "blue"))
print(make_colors("■ Magenta text", "magenta"))
print(make_colors("■ Cyan text", "cyan"))
print(make_colors("■ White text", "white"))

# Light variants
print(make_colors("■ Light Red", "lightred"))
print(make_colors("■ Light Green", "lightgreen"))
print(make_colors("■ Light Blue", "lightblue"))
print(make_colors("■ Light Yellow", "lightyellow"))

💡 Usage Examples

Basic Usage

from make_colors import make_colors

# Different ways to specify colors
print(make_colors("Full color names", "red", "white"))
print(make_colors("Using shortcuts", "r", "w"))
print(make_colors("Mixed notation", "red", "w"))

Separator Notation

# Using underscore separator
print(make_colors("Error occurred!", "red_white"))
print(make_colors("Success!", "green_black"))
print(make_colors("Warning!", "yellow_red"))

# Using dash separator
print(make_colors("Info message", "blue-white"))
print(make_colors("Debug info", "cyan-black"))

Advanced Examples

# System status display
def show_status(service, status):
    if status == "running":
        return make_colors(f"[✓] {service}", "lightgreen", "black")
    elif status == "stopped":
        return make_colors(f"[✗] {service}", "lightred", "black")
    else:
        return make_colors(f"[?] {service}", "lightyellow", "black")

print(show_status("Web Server", "running"))
print(show_status("Database", "stopped"))
print(show_status("Cache", "unknown"))

# Log level formatting
def log_message(level, message):
    colors = {
        "ERROR": ("lightwhite", "red"),
        "WARNING": ("black", "yellow"),
        "INFO": ("lightblue", "black"),
        "DEBUG": ("lightgrey", "black")
    }
    
    fg, bg = colors.get(level, ("white", "black"))
    return f"{make_colors(f' {level} ', fg, bg)} {message}"

print(log_message("ERROR", "Connection failed"))
print(log_message("WARNING", "Deprecated method used"))
print(log_message("INFO", "Server started successfully"))
print(log_message("DEBUG", "Variable value: 42"))

Progress Indicators

import time

def progress_bar(current, total, width=50):
    percentage = current / total
    filled = int(width * percentage)
    bar = "█" * filled + "░" * (width - filled)
    
    if percentage < 0.5:
        color = "red"
    elif percentage < 0.8:
        color = "yellow"
    else:
        color = "green"
    
    return make_colors(f"[{bar}] {current}/{total} ({percentage:.1%})", color)

# Simulate progress
for i in range(0, 101, 10):
    print(f"\r{progress_bar(i, 100)}", end="", flush=True)
    time.sleep(0.1)
print()  # New line after completion

Menu Systems

def create_menu():
    options = [
        ("1", "Start Application", "green"),
        ("2", "Settings", "yellow"),
        ("3", "Help", "blue"),
        ("4", "Exit", "red")
    ]
    
    print(make_colors(" 🎯 Main Menu ", "white", "blue"))
    print()
    
    for key, option, color in options:
        print(f"  {make_colors(key, 'white', color)} {option}")
    
    print()
    return input("Select option: ")

# Usage
choice = create_menu()

🌍 Environment Variables

Control make_colors behavior with environment variables:

Variable Values Description
MAKE_COLORS 0, 1 Disable/enable colors globally
MAKE_COLORS_FORCE 0, 1, True Force colors even when not supported
import os

# Disable colors
os.environ['MAKE_COLORS'] = '0'
print(make_colors("No colors", "red"))  # Output: "No colors" (no coloring)

# Force colors (useful for CI/CD or redirected output)
os.environ['MAKE_COLORS_FORCE'] = '1'
print(make_colors("Forced colors", "green"))  # Always colored

📚 API Reference

make_colors(string, foreground='white', background=None, attrs=[], force=False)

Colorizes a string with specified foreground and background colors.

Parameters:

  • string (str): Text to colorize
  • foreground (str): Foreground color name or shortcut
  • background (str, optional): Background color name or shortcut
  • attrs (list, optional): Text attributes (currently reserved for future use)
  • force (bool, optional): Force coloring even when not supported

Returns:

  • str: Colorized string with ANSI escape codes

Examples:

# Basic usage
make_colors("Hello", "red")

# With background
make_colors("Hello", "white", "red")

# Using shortcuts
make_colors("Hello", "w", "r")

# Separator notation
make_colors("Hello", "white_red")

# Force colors
make_colors("Hello", "red", force=True)

MakeColors.supports_color()

Class method to check if the current terminal supports color output.

Returns:

  • bool: True if colors are supported, False otherwise
from make_colors import MakeColors

if MakeColors.supports_color():
    print("Colors are supported!")
else:
    print("Colors not supported on this terminal")

🖥️ Platform Support

Windows

  • Windows 10+: Full support with native ANSI escape sequences
  • Older Windows: Limited support, requires ANSICON or similar tools
  • Windows Terminal: Excellent support with all features

Linux/Unix

  • Most terminals: Full support (xterm, gnome-terminal, konsole, etc.)
  • Tmux/Screen: Supported
  • SSH sessions: Supported when terminal supports colors

macOS

  • Terminal.app: Full support
  • iTerm2: Excellent support
  • Other terminals: Generally well supported

🛠️ Development Examples

Testing Colors

def test_all_colors():
    """Test all available colors"""
    colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
    light_colors = [f'light{color}' for color in colors if color != 'black'] + ['lightgrey']
    
    print("=== Standard Colors ===")
    for color in colors:
        print(make_colors(f"  {color.ljust(10)}", color, "black"))
    
    print("\n=== Light Colors ===")
    for color in light_colors:
        print(make_colors(f"  {color.ljust(15)}", color, "black"))

# Run the test
test_all_colors()

Color Compatibility Check

def check_color_support():
    """Check and display color support information"""
    from make_colors import MakeColors
    import sys
    import os
    
    print("=== Color Support Information ===")
    print(f"Platform: {sys.platform}")
    print(f"Colors supported: {MakeColors.supports_color()}")
    print(f"MAKE_COLORS env: {os.getenv('MAKE_COLORS', 'not set')}")
    print(f"MAKE_COLORS_FORCE env: {os.getenv('MAKE_COLORS_FORCE', 'not set')}")
    
    if hasattr(sys.stdout, 'isatty'):
        print(f"Is TTY: {sys.stdout.isatty()}")

check_color_support()

🎯 Best Practices

  1. Check color support before using in production applications
  2. Provide fallbacks for environments without color support
  3. Use environment variables to control color output
  4. Choose contrasting colors for better readability
  5. Test on multiple platforms to ensure compatibility
from make_colors import make_colors, MakeColors

def safe_print(text, fg="white", bg=None):
    """Safely print colored text with fallback"""
    if MakeColors.supports_color():
        print(make_colors(text, fg, bg))
    else:
        print(f"[{fg.upper()}] {text}")

# Usage
safe_print("This works everywhere!", "green")

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Hadi Cahyadi

Buy Me a Coffee

Donate via Ko-fi

Support me on Patreon


Made with ❤️ by Hadi Cahyadi for colorful terminal experiences!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

make_colors-3.42.tar.gz (19.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

make_colors-3.42-py2.py3-none-any.whl (16.2 kB view details)

Uploaded Python 2Python 3

File details

Details for the file make_colors-3.42.tar.gz.

File metadata

  • Download URL: make_colors-3.42.tar.gz
  • Upload date:
  • Size: 19.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for make_colors-3.42.tar.gz
Algorithm Hash digest
SHA256 e55c9ae5a0e7376129fb7865bdf8d8feca4419e95d21d841ce684c7a824a2929
MD5 4a4114675ed505eac1f73e47da04a59a
BLAKE2b-256 d74451297acc0ebb714e5e7ef51a9d81191f1cc46b7f69accde56f1bf902b80c

See more details on using hashes here.

File details

Details for the file make_colors-3.42-py2.py3-none-any.whl.

File metadata

  • Download URL: make_colors-3.42-py2.py3-none-any.whl
  • Upload date:
  • Size: 16.2 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for make_colors-3.42-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 8bbd7b478e45da65b1388e6fb4b77de9e12df343e4d9bb55cda72274cd7a2228
MD5 4e0cfdb8b22e763442aa48ecb1490e61
BLAKE2b-256 4ce9b493acc07befd2ab440d1026d5441bff99fbe97f8320fefcffc6d3b2d36d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page