Skip to content

Instantly share code, notes, and snippets.

@dideler
Last active April 8, 2024 04:15
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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
@keeganjk
Copy link

I'm making a Python script which I want to have colors and cross-compatibility. I added:

if 'Windows' in platform.system():
     os.system("echo 'device=c:\winnt\system32\ansi.sys' >> C:\Windows\System32\CONFIG.NT")

to make colors work with Windows. However, I got:

Access is denied.
1

How do I prevent this?

@pouya-abbasian
Copy link

This Is Very GOod! <3

@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