Skip to main content
 首页 » 编程设计

python之Curses 中的颜色

2025年05月04日11lori

我正在尝试为我的 curses 输出添加颜色。然而,挑战在于文本是通过单个长字符串打印的,即 self.all_results。有什么方法可以为字符串的单个部分添加颜色。

def main(self,stdscr): 
    x,y = 0,0 # size of the window 
    xx,yy = 50,200  # where to place window - up,across 
    pad = curses.newpad(150,150) # nlines, ncols 
    pad_pos = 0 
    exit = False 
 
    pad.addstr(4,0,str(self.all_results)) 
 
    while not exit: 
        sleep(0.2) 
        if self.timer != None: 
            if time() - start > self.timer: 
                self.stop = True 
                break 
 
        pad.addstr(0,0,str(self.format_results())) 
        pad.refresh(pad_pos,0, x,y, xx,yy) 
 
        cmd = stdscr.getch() 
        stdscr.nodelay(1) 
 
        if cmd != -1: 
            pad.refresh(pad_pos,0, x,y, xx,yy) 
            if len(self.format_results().split('\n')) > 100: 
                if  cmd == curses.KEY_DOWN: 
                    if pad_pos < len(self.format_results())+1: 
                        pad_pos += 1 
                    try: 
                        pad.refresh(pad_pos,0, x,y, xx,yy) 
                    except curses.error: 
                        pass 
                elif cmd == curses.KEY_UP: 
                    if pad_pos != 0: 
                        pad_pos -= 1 
                    try: 
                        pad.refresh(pad_pos,0, x,y, xx,yy) 
                    except curses.error: 
                        pass 

请您参考如下方法:

我会使用 re 来拆分字符串,然后使用 addstr 的非 x,y 形式,为每个字符串指定颜色部分。

#!/usr/bin/env python 
import curses 
from curses.wrapper import wrapper 
import re 
 
 
def addstr_colorized(win, y, x, s): 
    colors = {'OK': curses.COLOR_GREEN, 'ERROR': curses.COLOR_RED} 
    win.move(y, x) 
    pattern = r'({0:s})'.format( 
        '|'.join(r'\b{0:s}\b'.format(word) for word in colors.keys())) 
    s = re.split(pattern, s) 
    for s in s: 
        win.addstr(s, curses.color_pair(colors.get(s, 0))) 
 
 
def main(stdscr): 
    curses.init_pair(curses.COLOR_RED, 
                     curses.COLOR_RED, 
                     curses.COLOR_BLACK) 
    curses.init_pair(curses.COLOR_GREEN, 
                     curses.COLOR_GREEN, 
                     curses.COLOR_BLACK) 
 
    addstr_colorized(stdscr, 
                     4, 
                     0, 
                     "This line is OK.\nBut there is an ERROR in this line\n") 
    stdscr.refresh() 
    stdscr.getch() 
 
 
wrapper(main)