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

如何在Python格式化时添加ANSI转义码?求更优实现方案

解决Python中ANSI转义码格式化的更优方案

针对你遇到的ANSI颜色格式化问题,这里提供几种实用且高效的解决方案,规避你提到的所有痛点:

方案一:自定义字符串格式化器(推荐)

继承Python内置的string.Formatter,扩展格式语法,直接在格式字符串中指定颜色,既直观又不污染变量:

import string

class ColorFormatter(string.Formatter):
    # 集中定义颜色转义码
    COLOR_MAP = {
        'red': '\033[91m',
        'green': '\033[92m',
        'yellow': '\033[93m',
        'blue': '\033[94m',
        'reset': '\033[0m'
    }

    def format_field(self, value, format_spec):
        # 解析颜色格式指令,比如 {var:color=red}
        if format_spec.startswith('color='):
            color_key = format_spec.split('=')[1]
            color_code = self.COLOR_MAP.get(color_key, self.COLOR_MAP['reset'])
            # 应用颜色,并保留原有的格式化转换(如!r)
            formatted_val = super().format_field(value, '')
            return f"{color_code}{formatted_val}{self.COLOR_MAP['reset']}"
        # 处理普通格式化规则
        return super().format_field(value, format_spec)

# 使用示例
formatter = ColorFormatter()
log_output = formatter.format(
    "[{level:color=red}] {msg:color=green} | 追踪ID: {trace_id:color=yellow!r}",
    level="ERROR", msg="数据库连接超时", trace_id=78901
)
print(log_output)

该方案的优势:

  • 格式字符串可读性极强,直接通过:color=xxx标记颜色
  • 不污染变量列表,无需额外传入转义码变量
  • 完全兼容原有的格式化语法(如!r、数字格式等)
  • 颜色定义集中管理,修改或扩展颜色非常方便

方案二:上下文管理器自动处理颜色重置

适合需要批量着色某段输出的场景,自动处理颜色开启和重置,避免遗漏重置代码:

class ColorContext:
    COLORS = {
        'red': '\033[91m',
        'green': '\033[92m',
        'reset': '\033[0m'
    }

    def __init__(self, color):
        self.color_code = self.COLORS.get(color, self.COLORS['reset'])

    def __enter__(self):
        print(self.color_code, end='')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(self.COLORS['reset'], end='')

# 使用示例
with ColorContext('red'):
    print(f"错误代码: {404!r}", end=' ')
with ColorContext('green'):
    print(f"状态: 服务正常")

方案三:模块化装饰器着色

针对需要单独格式化的元素,用装饰器封装着色逻辑,代码模块化且避免拼接臃肿:

def colorize(color):
    COLOR_MAP = {
        'red': '\033[91m',
        'green': '\033[92m',
        'reset': '\033[0m'
    }
    def decorator(func):
        def wrapper(*args, **kwargs):
            content = func(*args, **kwargs)
            return f"{COLOR_MAP[color]}{content}{COLOR_MAP['reset']}"
        return wrapper
    return decorator

# 使用示例
@colorize('red')
def format_error(code):
    return f"错误[{code!r}]"

@colorize('green')
def format_success(msg):
    return f"成功: {msg}"

print(f"{format_error(500)} {format_success('数据同步完成')}")

内容的提问来源于stack exchange,提问作者xenoid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:48:41