_curses.error: addstr() returned ERR

Rob picture Rob · Aug 30, 2015 · Viewed 13k times · Source

Using Python, I am trying to write a script which will convert all typed characters into 'a' whenever you pressed space-bar. For example, i typed "python" and then space, then "python" will convert into "aaaaaa".

import argparse
import curses
import time

# Main Function
def main():
    screen=curses.initscr()
    curses.cbreak()
    screen.keypad(1)
    curses.echo()
    str_txt=''
    count = 0
    while True:
        s=screen.getch()
        if s != ord(' ') and s != ord('\x1b') and s != curses.KEY_BACKSPACE and s != curses.KEY_ENTER:
            str_txt += chr(int(s))
            count+=1

        if s == ord(' '):
            dim = screen.getyx()
            h = 'a'*len(str_txt)+' '
            screen.addstr(dim[0],dim[1]-count-1, h)     
            count=0
            str_txt=''
            screen.refresh()

        if s == curses.KEY_ENTER or s==10 or s==13:
            dim = screen.getyx()
            screen.move(dim[0]+1,0)
            screen.refresh()

        #if s == curses.KEY_BACKSPACE:
        #   dim = screen.getyx()
        #   screen.move(dim[0],dim[1])
        #   screen.refresh()

        if s == ord('\x1b'):
            curses.endwin()
            break

if __name__  == "__main__":
    main()

The above code works fine for 1st line, however, in the second line whenever i press spacebar, i am getting an error on line 22 saying "_curses.error: addstr() returned ERR"

EDITED: When I change screen.addstr(dim[0],dim1-count-1, h) to screen.addstr(dim[0],dim1-count, h), the error is eliminated but the output is not what I want. I have attached to output for your reference.

enter image description here

Answer

user4119159 picture user4119159 · Aug 30, 2015
if s != ord(' ') and s != ord('\x1b') and s != curses.KEY_BACKSPACE:
    str_txt += chr(int(s))
    count+=1

That if statement executes for the carriage return and\or newline char too I think, so I think your count is 1 over what you expected, due to the first line.

The addstr() returned ERR exception is because the cursor is being moved off screen (out of bound) due to:

screen.addstr(dim[0],dim[1]-count-1, h)

Since your count is +1 due to the carriage return (\r) at the end of your first line. The first if should check this and not increase the count. Try to add these checks s!=curses.KEY_ENTER and s!=10 and s!=13 to the first if and see if that helps. s!=10 will check the new line char (\n) (which may not be necessary in this case, but I am OCD). s!=13 will check the carriage return character (\r).