Skip to content

Instantly share code, notes, and snippets.

@dideler
Last active May 23, 2024 12:37
Show Gist options
  • Save dideler/3814182 to your computer and use it in GitHub Desktop.
Save dideler/3814182 to your computer and use it in GitHub Desktop.
Formatted output in the terminal (using Python)

Most (or all) of these methods make use of ANSI escape sequences.

Straight-up

For example, using a dictionary:

ansi = {'underline': '\033[4m', 'bold': '\033[1m', 'end':'\033[0m'}
print '{[bold]}Hello World{[end]}'.format(ansi, ansi)

Or you can also create a class with enable/disable methods:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

print '{.HEADER}Hello World{.ENDC}'.format(bcolors, bcolors)

This will work on *NIX, MacOS, and Windows (provided you enable ansi.sys). There are ANSI codes for setting the colour, moving the cursor, and more.

Libraries

E.g.:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')
  • has minimal Windows support
  • has Windows support!
  • no support for Windows command prompt
@DiegoVallejoDev
Copy link

DiegoVallejoDev commented Feb 1, 2021

I made a library some time ago

import sys
import os

def supports_color():
    """
    Returns True if the running system's terminal supports color, and False
    otherwise.
    """
    plat = sys.platform
    supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
    # isatty is not always implemented, #6223.
    is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
    return supported_platform and is_a_tty


class colors:
    HEADER  = '\033[95m' if supports_color() else ""
    OKBLUE  = '\033[94m' if supports_color() else ""
    OKCYAN  = '\033[96m' if supports_color() else ""
    OKGREEN = '\033[92m' if supports_color() else ""
    WARNING = '\033[93m' if supports_color() else ""
    FAIL    = '\033[91m' if supports_color() else ""
    ENDC    = '\033[0m'  if supports_color() else ""
    BOLD    = '\033[1m'  if supports_color() else ""
    UNDERLINE ='\033[4m' if supports_color() else ""

# TAGS ex: print(f"{WARN} Warning something")
INFO = f"{colors.BOLD}[i]{colors.ENDC}"                 if supports_color() else "[i]"
OK   = f"{colors.HEADER}[*]{colors.ENDC}"               if supports_color() else "[*]"
WARN = f"{colors.WARNING}[w]{colors.ENDC}"              if supports_color() else "[w]"
ERR  = f"{colors.BOLD}{colors.FAIL}[!]{colors.ENDC}"    if supports_color() else "[!]"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment