Before using the library, be sure to either
import colorlib
or
from colorlib import ... # Functions you need
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)
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()