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

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值