Skip to content Skip to sidebar Skip to footer

Display Inverse Video Text With Python On Terminal

Python has a curses module. Is there a simple way to use this module to display inverse video text? I don't want to do the full-blown curses application, just want the text to brin

Solution 1:

If you use the filter function (before initscr), the curses application will only update the current line of the screen (and will not clear the whole screen). That would be a minimal use of the curses library.

If you want a lower-level (no optimization, do it yourself), you would have to use the terminfo level of the library, i.e., these functions:

  • initscr with filter (since Python curses apparently has no interface to newterm)
  • tigetstr to read the capabilities for sgr, sgr0, smso, rmso, rev
  • tparm to format parameters for sgr if you use that
  • putp to write the strings read/formatted via tigetstr and tparm

The page Python curses.tigetstr Examples has some (mostly incomplete) examples using tigetstr, and reminds me that you could use setupterm as an alternative to newterm. If you visit that page searching for "curses.filter", it asserts there are examples of its use, but reading, I found nothing to report.

Further reading:

A demo with reverse-video:

import curses

curses.filter()
stdscr = curses.initscr()
stdscr.addstr("normal-")
stdscr.addstr("Hello world!", curses.A_REVERSE)
stdscr.addstr("-normal")
stdscr.refresh()
curses.endwin()
print

or

import curses

curses.setupterm()
curses.putp("normal-")
curses.putp(curses.tigetstr("rev"))
curses.putp("Hello world!")
curses.putp(curses.tigetstr("sgr0"))
curses.putp("-normal")

illustrates a point: text written with curses.putp bypasses the curses library optimization. You would use initscr or newterm to use the curses screen-optimization, but setupterm to not use it, just using the low-level capability- and output-functions.

Post a Comment for "Display Inverse Video Text With Python On Terminal"