Python curses not displaying colors, whereas C ncurses works fine

喜你入骨 提交于 2019-12-06 16:17:47

问题


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:


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.



来源:https://stackoverflow.com/questions/27855667/python-curses-not-displaying-colors-whereas-c-ncurses-works-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!