Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curses fails when calling addch on the bottom right corner

I am starting to learn curses in Python. I am using Python 3.5 on Mac OS X. When I try to write in the bottom-right corner, the program crashes with the following error:

$ python ex_curses.py
[...]
  File "ex_curses.py", line 19, in do_curses
    screen.addch(mlines, mcols, 'c')
  _curses.error: add_wch() returned ERR

The example program is:

import curses

def do_curses(screen):
    curses.noecho()
    curses.curs_set(0)
    screen.keypad(1)

    (line, col) = 12, 0
    screen.addstr(line, col, "Hello world!")
    line += 1
    screen.addstr(line, col, "Hello world!", curses.A_REVERSE)

    screen.addch(0, 0, "c")

    (mlines, mcols) = screen.getmaxyx()
    mlines -= 1
    mcols -= 1
    screen.addch(mlines, mcols, 'c')

    while True:
        event = screen.getch()
        if event == ord("q"):
            break
    curses.endwin()

if __name__ == "__main__":
    curses.wrapper(do_curses)

I have a feeling that I'm missing something obvious, but I don't know what.

like image 639
Giovanni Avatar asked Apr 03 '16 15:04

Giovanni


People also ask

What is curses module?

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. While curses is most widely used in the Unix environment, versions are available for Windows, DOS, and possibly other systems as well.

What is python curses?

What is curses? ¶ The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs.


2 Answers

window.insch(...) can place a character at the lower right of a window without advancing the cursor. Any character at that position will be bumped to the right without causing an error.

like image 113
Brian Killian Avatar answered Sep 30 '22 13:09

Brian Killian


For the future readers. After the @Thomas Dickey answer, I have added the following snippet to my code.

try: 
    screen.addch(mlines, mcols, 'c')
except _curses.error as e:
    pass 

Now my code looks like:

import curses
import _curses

def do_curses(screen):
    curses.noecho()
    curses.curs_set(0)
    screen.keypad(1)

    (line, col) = 12, 0
    screen.addstr(line, col, "Hello world!")
    line += 1
    screen.addstr(line, col, "Hello world!", curses.A_REVERSE)

    screen.addch(0, 0, "c")

    (mlines, mcols) = screen.getmaxyx()
    mlines -= 1
    mcols -= 1
    try:
        screen.addch(mlines, mcols, 'c')
    except _curses.error as e:
        pass

    while True:
        event = screen.getch()
        if event == ord("q"):
            break
    curses.endwin()

if __name__ == "__main__":
    curses.wrapper(do_curses)
like image 20
Giovanni Avatar answered Sep 30 '22 12:09

Giovanni