You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7(Windows 8.1)下termcolor颜色显示异常求助

Fix Termcolor Showing [31m Instead of Colored Text on Windows 8.1 Python 2.7

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:59:18