blob: 9264c0ed285feb87cb3c4eab66734266f075ef0b [file] [log] [blame]
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001\documentclass{howto}
2
3\title{Curses Programming with Python}
4
5\release{2.01}
6
7\author{A.M. Kuchling, Eric S. Raymond}
8\authoraddress{\email{amk@amk.ca}, \email{esr@thyrsus.com}}
9
10\begin{document}
11\maketitle
12
13\begin{abstract}
14\noindent
15This document describes how to write text-mode programs with Python 2.x,
16using the \module{curses} extension module to control the display.
17
18This document is available from the Python HOWTO page at
19\url{http://www.python.org/doc/howto}.
20\end{abstract}
21
22\tableofcontents
23
24\section{What is curses?}
25
26The curses library supplies a terminal-independent screen-painting and
27keyboard-handling facility for text-based terminals; such terminals
28include VT100s, the Linux console, and the simulated terminal provided
29by X11 programs such as xterm and rxvt. Display terminals support
30various control codes to perform common operations such as moving the
31cursor, scrolling the screen, and erasing areas. Different terminals
32use widely differing codes, and often have their own minor quirks.
33
34In a world of X displays, one might ask ``why bother''? It's true
35that character-cell display terminals are an obsolete technology, but
36there are niches in which being able to do fancy things with them are
37still valuable. One is on small-footprint or embedded Unixes that
38don't carry an X server. Another is for tools like OS installers
39and kernel configurators that may have to run before X is available.
40
41The curses library hides all the details of different terminals, and
42provides the programmer with an abstraction of a display, containing
43multiple non-overlapping windows. The contents of a window can be
44changed in various ways--adding text, erasing it, changing its
45appearance--and the curses library will automagically figure out what
46control codes need to be sent to the terminal to produce the right
47output.
48
49The curses library was originally written for BSD Unix; the later System V
50versions of Unix from AT\&T added many enhancements and new functions.
51BSD curses is no longer maintained, having been replaced by ncurses,
52which is an open-source implementation of the AT\&T interface. If you're
53using an open-source Unix such as Linux or FreeBSD, your system almost
54certainly uses ncurses. Since most current commercial Unix versions
55are based on System V code, all the functions described here will
56probably be available. The older versions of curses carried by some
57proprietary Unixes may not support everything, though.
58
59No one has made a Windows port of the curses module. On a Windows
60platform, try the Console module written by Fredrik Lundh. The
61Console module provides cursor-addressable text output, plus full
62support for mouse and keyboard input, and is available from
63\url{http://effbot.org/efflib/console}.
64
65\subsection{The Python curses module}
66
67Thy Python module is a fairly simple wrapper over the C functions
68provided by curses; if you're already familiar with curses programming
69in C, it's really easy to transfer that knowledge to Python. The
70biggest difference is that the Python interface makes things simpler,
71by merging different C functions such as \function{addstr},
72\function{mvaddstr}, \function{mvwaddstr}, into a single
73\method{addstr()} method. You'll see this covered in more detail
74later.
75
76This HOWTO is simply an introduction to writing text-mode programs
77with curses and Python. It doesn't attempt to be a complete guide to
Walter Dörwald9d9af8a2006-01-21 10:50:39 +000078the curses API; for that, see the Python library guide's section on
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +000079ncurses, and the C manual pages for ncurses. It will, however, give
80you the basic ideas.
81
82\section{Starting and ending a curses application}
83
84Before doing anything, curses must be initialized. This is done by
85calling the \function{initscr()} function, which will determine the
86terminal type, send any required setup codes to the terminal, and
87create various internal data structures. If successful,
88\function{initscr()} returns a window object representing the entire
89screen; this is usually called \code{stdscr}, after the name of the
90corresponding C
91variable.
92
93\begin{verbatim}
94import curses
95stdscr = curses.initscr()
96\end{verbatim}
97
98Usually curses applications turn off automatic echoing of keys to the
99screen, in order to be able to read keys and only display them under
100certain circumstances. This requires calling the \function{noecho()}
101function.
102
103\begin{verbatim}
104curses.noecho()
105\end{verbatim}
106
107Applications will also commonly need to react to keys instantly,
108without requiring the Enter key to be pressed; this is called cbreak
109mode, as opposed to the usual buffered input mode.
110
111\begin{verbatim}
112curses.cbreak()
113\end{verbatim}
114
115Terminals usually return special keys, such as the cursor keys or
116navigation keys such as Page Up and Home, as a multibyte escape
117sequence. While you could write your application to expect such
118sequences and process them accordingly, curses can do it for you,
119returning a special value such as \constant{curses.KEY_LEFT}. To get
120curses to do the job, you'll have to enable keypad mode.
121
122\begin{verbatim}
123stdscr.keypad(1)
124\end{verbatim}
125
126Terminating a curses application is much easier than starting one.
127You'll need to call
128
129\begin{verbatim}
130curses.nocbreak(); stdscr.keypad(0); curses.echo()
131\end{verbatim}
132
133to reverse the curses-friendly terminal settings. Then call the
134\function{endwin()} function to restore the terminal to its original
135operating mode.
136
137\begin{verbatim}
138curses.endwin()
139\end{verbatim}
140
141A common problem when debugging a curses application is to get your
142terminal messed up when the application dies without restoring the
143terminal to its previous state. In Python this commonly happens when
144your code is buggy and raises an uncaught exception. Keys are no
145longer be echoed to the screen when you type them, for example, which
146makes using the shell difficult.
147
148In Python you can avoid these complications and make debugging much
149easier by importing the module \module{curses.wrapper}. It supplies a
150function \function{wrapper} that takes a hook argument. It does the
151initializations described above, and also initializes colors if color
152support is present. It then runs your hook, and then finally
153deinitializes appropriately. The hook is called inside a try-catch
154clause which catches exceptions, performs curses deinitialization, and
155then passes the exception upwards. Thus, your terminal won't be left
156in a funny state on exception.
157
158\section{Windows and Pads}
159
160Windows are the basic abstraction in curses. A window object
161represents a rectangular area of the screen, and supports various
162 methods to display text, erase it, allow the user to input strings,
163and so forth.
164
165The \code{stdscr} object returned by the \function{initscr()} function
166is a window object that covers the entire screen. Many programs may
167need only this single window, but you might wish to divide the screen
168into smaller windows, in order to redraw or clear them separately.
169The \function{newwin()} function creates a new window of a given size,
170returning the new window object.
171
172\begin{verbatim}
173begin_x = 20 ; begin_y = 7
174height = 5 ; width = 40
175win = curses.newwin(height, width, begin_y, begin_x)
176\end{verbatim}
177
178A word about the coordinate system used in curses: coordinates are
179always passed in the order \emph{y,x}, and the top-left corner of a
180window is coordinate (0,0). This breaks a common convention for
181handling coordinates, where the \emph{x} coordinate usually comes
182first. This is an unfortunate difference from most other computer
183applications, but it's been part of curses since it was first written,
184and it's too late to change things now.
185
186When you call a method to display or erase text, the effect doesn't
187immediately show up on the display. This is because curses was
188originally written with slow 300-baud terminal connections in mind;
189with these terminals, minimizing the time required to redraw the
190screen is very important. This lets curses accumulate changes to the
191screen, and display them in the most efficient manner. For example,
192if your program displays some characters in a window, and then clears
193the window, there's no need to send the original characters because
194they'd never be visible.
195
196Accordingly, curses requires that you explicitly tell it to redraw
197windows, using the \function{refresh()} method of window objects. In
198practice, this doesn't really complicate programming with curses much.
199Most programs go into a flurry of activity, and then pause waiting for
200a keypress or some other action on the part of the user. All you have
201to do is to be sure that the screen has been redrawn before pausing to
202wait for user input, by simply calling \code{stdscr.refresh()} or the
203\function{refresh()} method of some other relevant window.
204
205A pad is a special case of a window; it can be larger than the actual
206display screen, and only a portion of it displayed at a time.
207Creating a pad simply requires the pad's height and width, while
208refreshing a pad requires giving the coordinates of the on-screen
209area where a subsection of the pad will be displayed.
210
211\begin{verbatim}
212pad = curses.newpad(100, 100)
213# These loops fill the pad with letters; this is
214# explained in the next section
215for y in range(0, 100):
216 for x in range(0, 100):
217 try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26 )
218 except curses.error: pass
219
220# Displays a section of the pad in the middle of the screen
221pad.refresh( 0,0, 5,5, 20,75)
222\end{verbatim}
223
224The \function{refresh()} call displays a section of the pad in the
225rectangle extending from coordinate (5,5) to coordinate (20,75) on the
226screen;the upper left corner of the displayed section is coordinate
227(0,0) on the pad. Beyond that difference, pads are exactly like
228ordinary windows and support the same methods.
229
230If you have multiple windows and pads on screen there is a more
231efficient way to go, which will prevent annoying screen flicker at
232refresh time. Use the methods \method{noutrefresh()} and/or
233\method{noutrefresh()} of each window to update the data structure
234representing the desired state of the screen; then change the physical
235screen to match the desired state in one go with the function
236\function{doupdate()}. The normal \method{refresh()} method calls
237\function{doupdate()} as its last act.
238
239\section{Displaying Text}
240
241{}From a C programmer's point of view, curses may sometimes look like
242a twisty maze of functions, all subtly different. For example,
243\function{addstr()} displays a string at the current cursor location
244in the \code{stdscr} window, while \function{mvaddstr()} moves to a
245given y,x coordinate first before displaying the string.
246\function{waddstr()} is just like \function{addstr()}, but allows
247specifying a window to use, instead of using \code{stdscr} by default.
248\function{mvwaddstr()} follows similarly.
249
250Fortunately the Python interface hides all these details;
251\code{stdscr} is a window object like any other, and methods like
252\function{addstr()} accept multiple argument forms. Usually there are
253four different forms.
254
255\begin{tableii}{|c|l|}{textrm}{Form}{Description}
256\lineii{\var{str} or \var{ch}}{Display the string \var{str} or
257character \var{ch}}
258\lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or
259character \var{ch}, using attribute \var{attr}}
260\lineii{\var{y}, \var{x}, \var{str} or \var{ch}}
261{Move to position \var{y,x} within the window, and display \var{str}
262or \var{ch}}
263\lineii{\var{y}, \var{x}, \var{str} or \var{ch}, \var{attr}}
264{Move to position \var{y,x} within the window, and display \var{str}
265or \var{ch}, using attribute \var{attr}}
266\end{tableii}
267
268Attributes allow displaying text in highlighted forms, such as in
269boldface, underline, reverse code, or in color. They'll be explained
270in more detail in the next subsection.
271
272The \function{addstr()} function takes a Python string as the value to
273be displayed, while the \function{addch()} functions take a character,
274which can be either a Python string of length 1, or an integer. If
275it's a string, you're limited to displaying characters between 0 and
276255. SVr4 curses provides constants for extension characters; these
277constants are integers greater than 255. For example,
278\constant{ACS_PLMINUS} is a +/- symbol, and \constant{ACS_ULCORNER} is
279the upper left corner of a box (handy for drawing borders).
280
281Windows remember where the cursor was left after the last operation,
282so if you leave out the \var{y,x} coordinates, the string or character
283will be displayed wherever the last operation left off. You can also
284move the cursor with the \function{move(\var{y,x})} method. Because
285some terminals always display a flashing cursor, you may want to
286ensure that the cursor is positioned in some location where it won't
287be distracting; it can be confusing to have the cursor blinking at
288some apparently random location.
289
290If your application doesn't need a blinking cursor at all, you can
291call \function{curs_set(0)} to make it invisible. Equivalently, and
292for compatibility with older curses versions, there's a
293\function{leaveok(\var{bool})} function. When \var{bool} is true, the
294curses library will attempt to suppress the flashing cursor, and you
295won't need to worry about leaving it in odd locations.
296
297\subsection{Attributes and Color}
298
299Characters can be displayed in different ways. Status lines in a
300text-based application are commonly shown in reverse video; a text
301viewer may need to highlight certain words. curses supports this by
302allowing you to specify an attribute for each cell on the screen.
303
304An attribute is a integer, each bit representing a different
305attribute. You can try to display text with multiple attribute bits
306set, but curses doesn't guarantee that all the possible combinations
307are available, or that they're all visually distinct. That depends on
308the ability of the terminal being used, so it's safest to stick to the
309most commonly available attributes, listed here.
310
311\begin{tableii}{|c|l|}{constant}{Attribute}{Description}
312\lineii{A_BLINK}{Blinking text}
313\lineii{A_BOLD}{Extra bright or bold text}
314\lineii{A_DIM}{Half bright text}
315\lineii{A_REVERSE}{Reverse-video text}
316\lineii{A_STANDOUT}{The best highlighting mode available}
317\lineii{A_UNDERLINE}{Underlined text}
318\end{tableii}
319
320So, to display a reverse-video status line on the top line of the
321screen,
322you could code:
323
324\begin{verbatim}
325stdscr.addstr(0, 0, "Current mode: Typing mode",
326 curses.A_REVERSE)
327stdscr.refresh()
328\end{verbatim}
329
330The curses library also supports color on those terminals that
331provide it, The most common such terminal is probably the Linux
332console, followed by color xterms.
333
334To use color, you must call the \function{start_color()} function
335soon after calling \function{initscr()}, to initialize the default
336color set (the \function{curses.wrapper.wrapper()} function does this
337automatically). Once that's done, the \function{has_colors()}
338function returns TRUE if the terminal in use can actually display
339color. (Note from AMK: curses uses the American spelling
340'color', instead of the Canadian/British spelling 'colour'. If you're
341like me, you'll have to resign yourself to misspelling it for the sake
342of these functions.)
343
344The curses library maintains a finite number of color pairs,
345containing a foreground (or text) color and a background color. You
346can get the attribute value corresponding to a color pair with the
347\function{color_pair()} function; this can be bitwise-OR'ed with other
348attributes such as \constant{A_REVERSE}, but again, such combinations
349are not guaranteed to work on all terminals.
350
351An example, which displays a line of text using color pair 1:
352
353\begin{verbatim}
354stdscr.addstr( "Pretty text", curses.color_pair(1) )
355stdscr.refresh()
356\end{verbatim}
357
358As I said before, a color pair consists of a foreground and
359background color. \function{start_color()} initializes 8 basic
360colors when it activates color mode. They are: 0:black, 1:red,
3612:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The curses
362module defines named constants for each of these colors:
363\constant{curses.COLOR_BLACK}, \constant{curses.COLOR_RED}, and so
364forth.
365
366The \function{init_pair(\var{n, f, b})} function changes the
367definition of color pair \var{n}, to foreground color {f} and
368background color {b}. Color pair 0 is hard-wired to white on black,
369and cannot be changed.
370
371Let's put all this together. To change color 1 to red
372text on a white background, you would call:
373
374\begin{verbatim}
375curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
376\end{verbatim}
377
378When you change a color pair, any text already displayed using that
379color pair will change to the new colors. You can also display new
380text in this color with:
381
382\begin{verbatim}
383stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1) )
384\end{verbatim}
385
386Very fancy terminals can change the definitions of the actual colors
387to a given RGB value. This lets you change color 1, which is usually
388red, to purple or blue or any other color you like. Unfortunately,
389the Linux console doesn't support this, so I'm unable to try it out,
390and can't provide any examples. You can check if your terminal can do
391this by calling \function{can_change_color()}, which returns TRUE if
392the capability is there. If you're lucky enough to have such a
393talented terminal, consult your system's man pages for more
394information.
395
396\section{User Input}
397
398The curses library itself offers only very simple input mechanisms.
399Python's support adds a text-input widget that makes up some of the
400lack.
401
402The most common way to get input to a window is to use its
403\method{getch()} method. that pauses, and waits for the user to hit
404a key, displaying it if \function{echo()} has been called earlier.
405You can optionally specify a coordinate to which the cursor should be
406moved before pausing.
407
408It's possible to change this behavior with the method
409\method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for
410the window becomes non-blocking and returns ERR (-1) when no input is
411ready. There's also a \function{halfdelay()} function, which can be
412used to (in effect) set a timer on each \method{getch()}; if no input
413becomes available within the number of milliseconds specified as the
414argument to \function{halfdelay()}, curses throws an exception.
415
416The \method{getch()} method returns an integer; if it's between 0 and
417255, it represents the ASCII code of the key pressed. Values greater
418than 255 are special keys such as Page Up, Home, or the cursor keys.
419You can compare the value returned to constants such as
420\constant{curses.KEY_PPAGE}, \constant{curses.KEY_HOME}, or
421\constant{curses.KEY_LEFT}. Usually the main loop of your program
422will look something like this:
423
424\begin{verbatim}
425while 1:
426 c = stdscr.getch()
427 if c == ord('p'): PrintDocument()
428 elif c == ord('q'): break # Exit the while()
429 elif c == curses.KEY_HOME: x = y = 0
430\end{verbatim}
431
432The \module{curses.ascii} module supplies ASCII class membership
433functions that take either integer or 1-character-string
434arguments; these may be useful in writing more readable tests for
435your command interpreters. It also supplies conversion functions
436that take either integer or 1-character-string arguments and return
437the same type. For example, \function{curses.ascii.ctrl()} returns
438the control character corresponding to its argument.
439
440There's also a method to retrieve an entire string,
441\constant{getstr()}. It isn't used very often, because its
442functionality is quite limited; the only editing keys available are
443the backspace key and the Enter key, which terminates the string. It
444can optionally be limited to a fixed number of characters.
445
446\begin{verbatim}
447curses.echo() # Enable echoing of characters
448
449# Get a 15-character string, with the cursor on the top line
450s = stdscr.getstr(0,0, 15)
451\end{verbatim}
452
453The Python \module{curses.textpad} module supplies something better.
454With it, you can turn a window into a text box that supports an
455Emacs-like set of keybindings. Various methods of \class{Textbox}
456class support editing with input validation and gathering the edit
457results either with or without trailing spaces. See the library
458documentation on \module{curses.textpad} for the details.
459
460\section{For More Information}
461
462This HOWTO didn't cover some advanced topics, such as screen-scraping
463or capturing mouse events from an xterm instance. But the Python
464library page for the curses modules is now pretty complete. You
465should browse it next.
466
467If you're in doubt about the detailed behavior of any of the ncurses
468entry points, consult the manual pages for your curses implementation,
469whether it's ncurses or a proprietary Unix vendor's. The manual pages
470will document any quirks, and provide complete lists of all the
471functions, attributes, and \constant{ACS_*} characters available to
472you.
473
474Because the curses API is so large, some functions aren't supported in
475the Python interface, not because they're difficult to implement, but
476because no one has needed them yet. Feel free to add them and then
477submit a patch. Also, we don't yet have support for the menus or
478panels libraries associated with ncurses; feel free to add that.
479
480If you write an interesting little program, feel free to contribute it
481as another demo. We can always use more of them!
482
483The ncurses FAQ: \url{http://dickey.his.com/ncurses/ncurses.faq.html}
484
485\end{document}