首页 > 解决方案 > 在 Python 诅咒中模拟 ANSI 颜色转义码

问题描述

我试图在我的 python-curses 应用程序中显示由tiv生成的“文本图像”。当然,我不能只打印文本,因为 (n)curses 不处理转义序列,所以我必须自己做。我被困在如何做背景颜色上。这是一段代码:

def makeData(data):
    out = []
    pos = 0
    ccol = ()
    while pos < len(data):
        if ord(data[pos]) == 27: #if it's a colour escape sequence
            pos += 2
            if data[pos] == "0": pos += 2; continue #tiv resets after every line, ignore that
            if data[pos] == "4": fg = False; bg = True
            else: fg = True; bg = False
            pos += 5 #skip 8;5;
            num = ""
            while data[pos] != "m":
                num += data[pos]
                pos += 1
            num = int(num)
            pos += 1
            ccol = (fg, bg, num)
        else: #otherwise, add the character with the current colour to the buffer
            out.append((ccol, data[pos]))
            pos += 1
    return out

def main(stdscr):
    curses.use_default_colors()
    for i in range(0, curses.COLORS):
    curses.init_pair(i + 1, i, -1)

    y = 1
    x = 1
    for char in self.data:
        if char[1] == "\n":
            y += 1
            x = 1
        else:
            self.s.addstr(y, x, char[1], curses.color_pair(char[0][2]))
            x += 1
                
    self.s.refresh()

这可以解析前景色和背景色,但是我被困在如何打印具有正确背景的字符上。现在,它适用于正确的前景但没有背景。

任何帮助都会非常有用,包括“这个代码不好做这个”:)

标签: pythonncursescursespython-curses

解决方案


推荐阅读