How to print colored terminal text in Python

Mar 06, 2024#python#cli

While traditional terminal output is often monochromatic, introducing colors allows developers to convey information more effectively and intuitively.

Colored text can be used to highlight important messages, errors, or warnings, making them stand out in a sea of text. Additionally, it can help organize and categorize information, providing a quick and visually distinct way to differentiate between various components or types of output.

There are several ways to print colored text in Python, depending on your needs and preferences. Here are the most common approaches:

  • If you need cross-platform compatibility, colorama or termcolor are good choices.
  • For fine-grained control over formatting, consider using ANSI escape codes directly.
  • If you need advanced formatting features beyond just color, explore the Rich library.

Remember that colored text output might not be displayed correctly in all environments, so make sure your target audience can see the formatting as intended.

Using ANSI escape codes directly

You can manually insert ANSI escape sequences into your print statements. This offers fine-grained control but requires knowledge of the specific codes for colors and styles.

print("\033[31mThis is red text!\033[0m")  # Red text
print("\033[32mThis is green text!\033[0m")  # Green text

The \033 in the code print("\033[31mThis is red text!\033[0m") is the escape character in ASCII. In this context, it is used to signal the start of an ANSI escape code sequence.

The specific sequence \033[31m is interpreted as follows:

  • \033: The escape character.
  • [: The left square bracket, which starts the control sequence.
  • 31: The code for setting the text color to red.
  • m: The letter “m” terminates the sequence.

Similarly, \033[0m is another ANSI escape code sequence:

  • \033: The escape character.
  • [: The left square bracket, which starts the control sequence.
  • 0: The code for resetting the text formatting to default.
  • m: The letter “m” terminates the sequence.

This sequence \033[0m resets any text formatting changes made by previous escape codes, ensuring that subsequent text is displayed with the default formatting.

ANSI escape codes are a set of special sequences of characters that control the terminal’s behavior. These codes can be used to change text color, background color, positioning, cursor movement, and more.

ANSI escape codes may not work consistently across all terminals. Windows consoles have limited support for ANSI escape codes. You might need additional libraries for better color control on Windows.

While convenient, extensive use of escape codes can make code less readable. Consider using a library for complex formatting tasks.

Using colorama library

This is a popular and easy-to-use library that provides cross-platform support for colored text output. Colorama provides a set of constants and functions that make it easier to use ANSI escape codes without memorizing the specific sequences.

from colorama import Fore, Back, Style

print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

It attempts to handle platform-specific differences in how terminals interpret escape codes, making your code work consistently across different operating systems.

You can write code that displays colored output consistently on different operating systems without worrying about specific terminal compatibility issues.

Using termcolor library

Termcolor is another Python library similar to Colorama, used for printing colored text to the terminal. However, unlike Colorama, it focuses specifically on colorizing text output, without offering functionalities for other formatting styles like bold, underline, or dimming.

from termcolor import colored

print(colored('This is red text!', 'red'))
print(colored('This is green text!', 'green'))

Using rich library

This library offers more advanced formatting features including coloring, and supports a BBCode-like syntax for easy manipulation.

To effortlessly add rich output to your application, you can import the rich print method, which has the same signature as the builtin Python function. You can then print strings or objects to the terminal in the usual way. Rich will do some basic syntax highlighting and format data structures to make them easier to read.

from rich import print

print("[red]This is red text![/]")
print("[bold magenta]This is bold magenta text![/]")

Rich supports a simple markup which you can use to insert color and styles virtually everywhere Rich would accept a string. Console markup uses a syntax inspired by bbcode. If you write the style in square brackets, e.g. [bold red], that style will apply until it is closed with a corresponding [/bold red].

Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box.

Using colored library

Colored, it’s a simple Python library for color and formatting in terminal. Collection of color codes and names for 256 color terminal setups.

from colored import Fore, Back, Style

print(f"{Fore.white}{Back.green}Colored is Awesome!!!{Style.reset}")
print("Reset to default settings")

These modules provide class attributes handled, and you can easily reference your color or style you want. You can use the attributes with lower case or capitalize as well.