Python 诅咒不显示颜色,而 C ncurses 工作正常

Ale*_*lex 3 python curses ncurses python-curses

我似乎无法让 Python curses 模块显示颜色,而 ncurses C 库工作正常。这是一个应该可以工作的简单脚本:

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)
Run Code Online (Sandbox Code Playgroud)

我只能看到“按任意键退出。”。我知道“Hello world”是因为换行而写的,但我看不到文本。我尝试了各种颜色对,但只有 0,即白色,有效。

不使用包装器,即

  stdscr = curses.initscr()
  curses.start_color()
  main(stdscr)
  curses.endwin()
Run Code Online (Sandbox Code Playgroud)

没有帮助。

我在具有黑色背景的 XTerm(312) 和具有白色背景的 urxvt v9.20 上对其进行了测试。我在 Debian jessie 上,使用 bash 和 Python 2.7。

我运行了一个使用 ncurses 的旧 C 脚本,它可以很好地显示颜色,所以我假设我做错了什么,或者 python 库有问题。我下载了一个名为 colortest-python 的包,它也能够显示颜色,尽管它不使用curses来这样做(只是为了测试终端是否能够显示颜色)。

Álv*_*mez 5

您需要在开头添加以下几行来初始化颜色

curses.start_color()
curses.use_default_colors()
Run Code Online (Sandbox Code Playgroud)

然后你需要初始化颜色对

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
Run Code Online (Sandbox Code Playgroud)

例如,这会将第一对初始化为红色前景和白色背景。之后,您使用 int 值作为函数中的第一个参数而不是 curses.color_pair() 中的 curses.COLORS 传递,颜色将正确显示。