Before doing anything, curses must be initialized. This is done by
calling the initscr() function, which will determine the
terminal type, send any required setup codes to the terminal, and
create various internal data structures. If successful,
initscr() returns a window object representing the entire
screen; this is usually called stdscr
, after the name of the
corresponding C
variable.
import curses stdscr = curses.initscr()
Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read keys and only display them under certain circumstances. This requires calling the noecho() function.
curses.noecho()
Applications will also commonly need to react to keys instantly, without requiring the Enter key to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode.
curses.cbreak()
Terminals usually return special keys, such as the cursor keys or navigation keys such as Page Up and Home, as a multibyte escape sequence. While you could write your application to expect such sequences and process them accordingly, curses can do it for you, returning a special value such as curses.KEY_LEFT. To get curses to do the job, you'll have to enable keypad mode.
stdscr.keypad(1)
Terminating a curses application is much easier than starting one. You'll need to call
curses.nobreak(); curses.keypad(0); curses.echo()
to reverse the curses-friendly terminal settings. Then call the endwin() function to restore the terminal to its original operating mode.
curses.endwin()
A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer be echoed to the screen when you type them, for example, which makes using the shell difficult.
In Python you can avoid these complications and make debugging much easier by importing the module curses.wrapper. It supplies a function wrapper that takes a hook argument. It does the initializations described above, and also initializes colors if color support is present. It then runs your hook, and then finally deinitializes appropriately. The hook is called inside a try-catch clause which catches exceptions, performs curses deinitialization, and then passes the exception upwards. Thus, your terminal won't be left in a funny state on exception.