5. User Input

curses offers only very simple input mechanisms. Windows have a getch() method that pauses, and waits for the user to hit a key, displaying it if echo() has been called earlier. You can optionally specify a coordinate to which the cursor should be moved before pausing. getch() returns an integer; if it's between 0 and 255, it represents the ASCII code of the key pressed. Values greater than 255 are special keys such as Page Up, Home, or the cursor keys. You can compare the value returned to constants such as curses.KEY_PPAGE, curses.KEY_HOME, or curses.KEY_LEFT. Usually the main loop of your program might look like this:

while (1)
    c = stdscr.getch()
    if c == ord('p'): PrintDocument()
    elif c == ord('q'): break  # Exit the while()
    elif c == curses.KEY_HOME: x = y = 0

There's also a method to retrieve an entire string, getstr(). It isn't used very often, because its functionality is quite limited; the only editing keys available are the backspace key and the Enter key, which terminates the string. It can optionally be limited to a fixed number of characters.

curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line 
s = stdscr.getstr(0,0, 15)

In future versions of this HOWTO, I'd like to include an implementation of a fancy string entry function that allows full editing. If you write such a function, send me a copy and it'll be added to the next version of this document.