5 User Input

The curses library itself offers only very simple input mechanisms. Python's support adds a text-input widget that makes up some of the lack.

The most common way to get input to a window is to use its 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.

It's possible to change this behavior with the method nodelay(). After nodelay(1), getch() for the window becomes non-blocking and returns ERR (-1) when no input is ready. There's also a halfdelay() function, which can be used to (in effect) set a timer on each getch(); if no input becomes available within the number of milliseconds specified as the argument to halfdelay(), curses throws an exception.

The getch() method 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 will look something 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

The curses.ascii module supplies ASCII class membership functions that take either integer or 1-character-string arguments; these may be useful in writing more readable tests for your command interpreters. It also supplies conversion functions that take either integer or 1-character-string arguments and return the same type. For example, curses.ascii.ctrl() returns the control character corresponding to its argument.

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)

The Python curses.textpad module supplies something better. With it, you can turn a window into a text box that supports an Emacs-like set of keybindings. Various methods of Textbox class support editing with input validation and gathering the edit results either with or without trailing spaces. See the library documentation on curses.textpad for the details.