How do I print colored text to the terminal?
To print colored text in Python, use ANSI codes
such as the ones below:
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.
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):
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.
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.
Was this article helpful?