Python 2.7(Windows 8.1)下termcolor颜色显示异常求助
Hey there, I’ve run into this exact issue before on Windows—let’s get your colored text working properly!
Why This Happens
The [31m and [0m you’re seeing are ANSI escape codes, which tell terminals how to color text. Unfortunately, the default Windows Command Prompt (cmd) on 8.1 doesn’t natively recognize these codes—it just prints them as plain text instead of applying the color.
Solutions to Try
1. Use Colorama to Add ANSI Support (Easiest Fix)
Colorama is a tiny library that translates ANSI codes into Windows-native console commands. Here’s how to set it up:
- First, install Colorama using pip (for Python 2.7, make sure you’re using pip2 if you have multiple Python versions installed):
pip install colorama - Modify your code to initialize Colorama before using termcolor:
from colorama import init from termcolor import colored # Initialize colorama to enable ANSI code support on Windows init() print colored('Hello world', 'red')
Run this script again, and you should see red "Hello world" instead of the raw codes!
2. Switch to a Terminal That Supports ANSI Codes
If you don’t want to add another library, use a terminal emulator that natively understands ANSI codes. For Windows 8.1, Git Bash is a great option—it’s free, easy to install, and will render termcolor’s output correctly without any extra code. Just run your Python script inside Git Bash instead of cmd.
3. (Less Recommended) Manually Handle Console Colors
You could skip termcolor entirely and use Windows’ own console API via the ctypes module, but this is way more work than using Colorama. Stick with the first two solutions for simplicity.
内容的提问来源于stack exchange,提问作者vijay Dave

