Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last character of a window in python + curses

Tags:

python

ncurses

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?

like image 761
Jerome Avatar asked Aug 15 '11 08:08

Jerome


People also ask

Does curses work on Windows Python?

The Windows version of Python doesn't include the curses module. A ported version called UniCurses is available.

How do you clear the screen curse in Python?

To clear characters until the end of the line, use clrtoeol(), To clear characters until the end of the window, use clrtobot().

How do you get curses in Python?

The curses package comes with the Python standard library. In Linux and Mac, the curses dependencies should already be installed so there is no extra steps needed. On Windows, you need to install one special Python package, windows-curses available on PyPI to add support.


2 Answers

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, " ")
like image 157
Jerome Avatar answered Oct 21 '22 08:10

Jerome


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.

like image 23
Jeet Avatar answered Oct 21 '22 08:10

Jeet