How to print colored text in Python?

前端 未结 30 2833
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  逝去的感伤
    2020-11-21 05:27

    Here's a curses example:

    import curses
    
    def main(stdscr):
        stdscr.clear()
        if curses.has_colors():
            for i in xrange(1, curses.COLORS):
                curses.init_pair(i, i, curses.COLOR_BLACK)
                stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
                stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
                stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
                stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
                stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
                stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
                stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
        stdscr.refresh()
        stdscr.getch()
    
    if __name__ == '__main__':
        print "init..."
        curses.wrapper(main)
    

提交回复
热议问题