Python诅咒不显示颜色,而C ncurses可以正常工作 [英] Python curses not displaying colors, whereas C ncurses works fine

查看:124
本文介绍了Python诅咒不显示颜色,而C ncurses可以正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我只能看到按任意键退出".我知道因为有新行而正在编写"Hello world",但看不到文本.我尝试了各种颜色对,但只有0(即白色)有效.

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.

不使用包装器,即

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

没有帮助.

我在具有黑色bg的XTerm(312)和具有白色bg的urxvt v9.20上进行了测试.我正在使用bash和Python 2.7在Debian jessie上.

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.

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

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).

推荐答案

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

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

curses.start_color()
curses.use_default_colors()

然后您需要o用

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

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

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.

这篇关于Python诅咒不显示颜色,而C ncurses可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆