在Python诅咒中模拟ANSI颜色转义码

2024-10-08 23:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

这可以解析前景和背景颜色,但是我一直在研究如何用正确的背景打印字符。现在,它使用正确的前景,但没有背景

任何帮助都会非常有用,包括“此代码不好,请改为执行此操作”:


Tags: theposselfdataifoutelsenum

热门问题