Jerome
Jerome

Reputation: 2370

Last character of a window in python + curses

The following program raises an error:

import curses

def test(scr):
  top = curses.newwin(1, 10, 0, 0)
  top.addstr(0, 9, "X")

curses.wrapper(test)

It looks like whenever I try to use addstr() to write a character in the last column of the last line of a window (even when it is smaller than the screen), it raises an error. I don't want to scroll, I don't care about the cursor's position. All I want is being able to write characters in every single position of the window. Is it possible at all? How can I do this?

Upvotes: 15

Views: 2113

Answers (2)

Jeet
Jeet

Reputation: 39827

Turns out that curses actually does end up writing to that last position: it just raises an error right afterwards.

So, if you can live with the following hack/inelegance:

#! /usr/bin/env python
import curses

def test(scr):
    top = curses.newwin(1, 10, 0, 0)
    try:
        top.addstr(0, 9, "X")
    except curses.error:
        pass

curses.wrapper(test)

i.e., trapping and ignoring the error, then the code will be much simpler both in design and implementation.

Upvotes: 8

Jerome
Jerome

Reputation: 2370

It looks like simply writing the last character of a window is impossible with curses, for historical reasons.

The only workaround I could find consists in writing the character one place to the left of its final destination, and pushing it with an insert. The following code will push the "X" to position 9:

top = curses.newwin(1, 10, 0, 0)
top.addstr(0, 8, "X")
top.insstr(0, 8, " ")

Upvotes: 12

Related Questions