Explain Codes LogoExplain Codes Logo

How do I print colored text to the terminal?

python
colorama
curses
terminal-ui
Alex KataevbyAlex Kataev·Aug 11, 2024
TLDR

To print colored text in Python, use ANSI codes such as the ones below:

print("\033[31mRed Text\033[0m")

In this example, "\033[31m" indicates red color, and "\033[0m" resets the color back to default.

Cross-platform compatibility - colorama

ANSI codes work well on Linux and Mac but might not perform as expected on Windows. The colorama library allows for cross-platform colored output by translating ANSI codes into Windows API calls.

from colorama import init, Fore init() # Don't forget to put your seatbelt on! print(F"{Fore.RED}Red Text{Fore.RESET}") # Paint it red

More than colors - curses

When you need to deal with multiple text blocks, dynamic window resizing, or even keyboard input, the curses module steps in.

Although curses can be overwhelming due to its low-level interface, a little patience and practice gets you far.

Here's a compact hello world example (curses style):

import curses def main(stdscr): curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) stdscr.addstr("Red on White Text", curses.color_pair(1)) # Who doesn't love red on white? stdscr.refresh() stdscr.getkey() curses.wrapper(main) # Wrapping it all up nicely

Note that we're using curses.wrapper() to manage the initialization and cleanup aspects.

Doing ASCII art in the terminal

You can enhance your terminal output by adding ASCII graphics. Shapes and lines can be drawn using ASCII or Extended ASCII characters to separate information.

Here's an ASCII magic box:

+----+
|    |
+----+

You can use this box to highlight important information or just to show off your ASCII craftsmanship. Check out resources like the Dwarf Fortress Wiki for more ASCII tilesets and art.

Managing ANSI escape sequences on Windows

To use ANSI escape sequences on Windows, ANSICON or VT100 emulation could be required.

Modern Windows 10 Command Prompt and PowerShell support ANSI escape sequences natively, but the feature might need to be activated manually.

# Activating VT100 C:\> reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 # VT100, I am your father!

Terminal UI: Next level

The Text Mode Demo Contest website is a true wellspring of inspiration. It's fascinating to see how you can mix color, movement, and sound in console applications.

Master the terminal graphics

Python Curses HowTO is a valuable resource for anyone looking to dominate terminal graphics using Python. It provides comprehensive tutorials and documentation to master the craft of text-based user interfaces.