使用Python诅咒自定义RGB颜色

时间:2016-04-22 20:32:50

标签: python ncurses curses

我正在使用标准库中的curses模块在​​Python中编写程序。

如果我的程序不能使用我用RGB三元组指定的自定义颜色,我希望我的程序退出。

所以我有一些看起来像的初学者代码:

import curses

def main(stdscr):
  if not curses.can_change_color():
    raise Exception('Cannot change color')

  curses.init_color(curses.COLOR_BLACK, 999,   0,   0)
  curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
  curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
  stdscr.addstr('hello', curses.color_pair(1))
  stdscr.addstr(' world', curses.color_pair(2))
  stdscr.getch()

curses.wrapper(main)

我得到的结果是:

enter image description here

我预计黑色会被红色取代。

我误解了docs吗?如何让curses尊重我想要使用的自定义RGB颜色?或者至少失败并告诉我终端不支持它?

诅咒here的文档似乎暗示,如果失败,它将返回错误,而CPython源似乎propagate curses errors非常忠实。

如果它是相关的,我在OS X 10.11上,我正在使用Homebrew安装的Python3上进行测试。但是我也可以使用OS X的内置Python解释器获得相同的效果。

编辑:

略微修改示例代码以显示颜色内容:

import curses

def main(stdscr):
  if not curses.can_change_color():
    raise Exception('Cannot change color')

  stdscr.addstr(1, 0, repr(curses.color_content(curses.COLOR_BLACK)))
  curses.init_color(curses.COLOR_BLACK, 999,   0,   0)
  curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
  curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
  stdscr.addstr(0, 0, 'hello', curses.color_pair(1))
  stdscr.addstr(' world', curses.color_pair(2))
  stdscr.addstr(2, 0, repr(curses.color_content(curses.COLOR_BLACK)))
  stdscr.getch()

curses.wrapper(main)

这次的结果是: enter image description here

1 个答案:

答案 0 :(得分:1)

屏幕截图可能是Terminal.app;在快速检查中,它不遵守用于改变颜色的转义序列。另一方面,iTerm2确实使用了这些转义序列。

如果您正在使用Terminal.app,将TERM设置为xterm-256color是没有意义的,因为与xterm存在大量差异。终端数据库中有discussion作为评论,您可能会发现一些有趣的内容。

相关问题