Python curses not displaying colors, whereas C ncu

2019-04-17 08:58发布

I can't seem to get the Python curses module to display colors, whereas the ncurses C library works fine. Here is a simple script that should work:

import curses

def main(stdscr):

  if not curses.has_colors(): raise
  stdscr.addstr("Hello world\n", curses.color_pair(curses.COLOR_RED))
  stdscr.addstr("Press any key to exit.\n")
  stdscr.refresh()
  while stdscr.getch() == -1: pass

if __name__ == '__main__':
  curses.wrapper(main)

I can only see "Press any key to exit.". I know "Hello world" is being written because of the new line, but I can't see the text. I attempted various color pairs, but only 0, i.e. white, works.

Not using the wrapper, i.e.

  stdscr = curses.initscr()
  curses.start_color()
  main(stdscr)
  curses.endwin()

Didn't help.

I tested it on XTerm(312), which has a black bg, and urxvt v9.20, which has a white one. I am on Debian jessie, using bash and Python 2.7.

I ran an old C script I had that uses ncurses and it displays colors nicely, so I assume either I'm doing something wrong or there's something wrong with the python library. I downloaded a package called colortest-python and it was able to display color too, although it doesn't use curses to do so (only to test if the terminal is capable of displaying colors).

1条回答
劳资没心,怎么记你
2楼-- · 2019-04-17 09:10

you need to add the following lines at the beginning to initialize colors

curses.start_color()
curses.use_default_colors()

You then need o initialize color pairs with

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

This will initialize the first pair to red foreground and white background for example. After that you use the int value you pass as the first arg in the function instead of curses.COLORS in curses.color_pair() and the colors will appear properly.

查看更多
登录 后发表回答