Skip to content

Instantly share code, notes, and snippets.

@Ryan-M-Smith
Last active November 1, 2023 04:00
Show Gist options
  • Save Ryan-M-Smith/5b2ae0228f4ad6820f366497dd88f93e to your computer and use it in GitHub Desktop.
Save Ryan-M-Smith/5b2ae0228f4ad6820f366497dd88f93e to your computer and use it in GitHub Desktop.
A simple Python library to allow you to change the color of terminal text.

ColorLib

Function wrappers for the ANSI 256-color lookup table.

How to use

Before using the library, be sure to either

import colorlib

or

from colorlib import ... # Functions you need

Setting the text color

To set the terminal text color, use the colorlib.printclr function. You can either set the color using any of the predefined colors, or any number between 0 and 255 on the ANSI lookup table.

The predefined colors are "red", "orange", "yellow", "dark-green", "lime-green", "blue", "indigo", "violet", "purple" (lighter than violet), "pink", "black", "white", and "gray". The full lookup table can be found here.

# An example using a predefined color
colorlib.printclr("Hello, World!", "red")

# An example using a number
colorlib.printclr("Hello, World!", 9) # 9 is the code for red (#FF0000) on the table

Just like the builtin print function, you can provide optional sep and end arguments. By default, the sep argument is None and the end argument is "". This is so the color can be changed multiple times in one line without worrying about a newline being added. For functionality similar to Python's print, use end="\n" in the function call.

# Prints "Hello, World!", but the "Hello," is red and the " World!" is blue.
colorlib.printclr("Hello,", "red")
colorlib.printclr(" World!", "blue")

# The same thing, but with the default `print` functionality (i.e., each word on its own line).
colorlib.printclr("Hello,", "red", end="\n")
colorlib.printclr(" World!", "blue", end="\n)

Setting a default text color

If you set a default text color, you can reset your terminal color to that default color. To set the defaut color, use the colorlib.set_default function, and reset to the color with colorlib.reset.

# If you use a black terminal with white text, set your default color to white.
colorlib.set_default("white") # Alternatively, `colorlib.set_default(15)`

... # Do something with the library

# Reset the color; all following text will be your default color
colorlib.reset()
#
# FILENAME: colorlib.py
# DESCRIPTION: Function wrappers for the ANSI 256-color lookup table
# CREATED: 2020-12-06 @ 9:01 PM
# Copyright (c) 2020 by Ryan Smith <[email protected]>
#
""" Function wrappers for the ANSI 256-color lookup table. """
import codecs
from typing import Union, Optional, AnyStr
__default_color = Union[str, int]
__COLORS = {
"red": r"\033[38;5;9m", # Hex: #FF0000
"orange": r"\033[38;5;202m", # Hex: #FF5F00
"yellow": r"\033[38;5;11m", # Hex: #FFFF00
"dark-green": r"\033[38;5;2m", # Hex: #008000
"lime-green": r"\033[38;5;10m", # Hex: #00FF00
"blue": r"\033[38;5;12m", # Hex: #0000FF
"indigo": r"\033[38;5;18m", # Hex: #000087
"violet": r"\033[38;5;5m", # Hex: #800080
"purple": r"\033[38;5;91m", # Hex: #8700AF
"pink": r"\033[38;5;13m", # Hex: #FF00FF
"black": r"\033[38;5;0m", # Hex: #000000
"white": r"\033[38;5;15m", # Hex: #FFFFFF
"gray": r"\033[38;5;8m" # Hex: #808080
}
def printclr(text: AnyStr, color: Union[str, int], *, sep: Optional[AnyStr] = None, end: Optional[AnyStr] = ""):
"""
Print text to the terminal using a pre-defined color name OR a valid number in 8-bit 256-color mode.
Valid color names are \"red\", \"orange\", \"yellow\", \"dark-green\", \"lime-green\", \"blue\", \"indigo\",
\"violet\", \"purple\" (lighter than violet), \"pink\", \"black\", \"white\", and \"gray\".
Valid indicies are 0 - 255.
The `sep` and `end` arguments are also included to match with the Python `print` function. `sep` is set to `None`
by default, and `end` is set to `\"\"` (an empty string) so the text color can be changed multiple times on the same
line without a new line being created. To achieve the default Python `print` functionality, set `end` to `\"\\n\"`.
"""
try:
if (type(color) is str) and (color in list(__COLORS.keys())):
# Print using a pre-defined color
print(f"{codecs.decode(__COLORS.get(color), 'unicode_escape')}{text}", sep=sep, end=end)
else:
# Print using a number
code = f"\033[38;5;{str(color)}m"
print(f"{code}{text}", sep=sep, end=end)
except Exception:
print("There was a problem.")
def set_default(color: Union[str, int]):
""" Sets the user's preferred default terminal color. """
global __default_color
__default_color = color
def reset():
""" Reset the terminal color to the user's default color. """
global __default_color
printfclr("", color=__default_color)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment