blob: 3e4cada820ee4365fd7950ac7bb368cda1104270 [file] [log] [blame]
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001\documentclass{howto}
2
3\title{Curses Programming with Python}
4
Thomas Wouters9fe394c2007-02-05 01:24:16 +00005\release{2.02}
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00006
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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000150\function{wrapper()} function that takes a callable. It does the
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000151initializations described above, and also initializes colors if color
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000152support is present. It then runs your provided callable and finally
153deinitializes appropriately. The callable is called inside a try-catch
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000154clause 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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000162methods to display text, erase it, allow the user to input strings,
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000163and 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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000226screen; the upper left corner of the displayed section is coordinate
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000227(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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000232refresh time. Use the \method{noutrefresh()} method
233of each window to update the data structure
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000234representing 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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000257character \var{ch} at the current position}
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000258\lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000259character \var{ch}, using attribute \var{attr} at the current position}
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000260\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,
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000274which can be either a Python string of length 1 or an integer. If
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000275it'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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000334To use color, you must call the \function{start_color()} function soon
335after calling \function{initscr()}, to initialize the default color
336set (the \function{curses.wrapper.wrapper()} function does this
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000337automatically). Once that's done, the \function{has_colors()}
338function returns TRUE if the terminal in use can actually display
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000339color. (Note: curses uses the American spelling 'color', instead of
340the Canadian/British spelling 'colour'. If you're used to the British
341spelling, you'll have to resign yourself to misspelling it for the
342sake of these functions.)
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000343
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
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000403\method{getch()} method. \method{getch()} pauses and waits for the
404user to hit a key, displaying it if \function{echo()} has been called
405earlier. You can optionally specify a coordinate to which the cursor
406should be moved before pausing.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000407
408It's possible to change this behavior with the method
409\method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000410the window becomes non-blocking and returns \code{curses.ERR} (a value
411of -1) when no input is ready. There's also a \function{halfdelay()}
412function, which can be used to (in effect) set a timer on each
413\method{getch()}; if no input becomes available within the number of
414milliseconds specified as the argument to \function{halfdelay()},
415curses raises an exception.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000416
417The \method{getch()} method returns an integer; if it's between 0 and
418255, it represents the ASCII code of the key pressed. Values greater
419than 255 are special keys such as Page Up, Home, or the cursor keys.
420You can compare the value returned to constants such as
421\constant{curses.KEY_PPAGE}, \constant{curses.KEY_HOME}, or
422\constant{curses.KEY_LEFT}. Usually the main loop of your program
423will look something like this:
424
425\begin{verbatim}
426while 1:
427 c = stdscr.getch()
428 if c == ord('p'): PrintDocument()
429 elif c == ord('q'): break # Exit the while()
430 elif c == curses.KEY_HOME: x = y = 0
431\end{verbatim}
432
433The \module{curses.ascii} module supplies ASCII class membership
434functions that take either integer or 1-character-string
435arguments; these may be useful in writing more readable tests for
436your command interpreters. It also supplies conversion functions
437that take either integer or 1-character-string arguments and return
438the same type. For example, \function{curses.ascii.ctrl()} returns
439the control character corresponding to its argument.
440
441There's also a method to retrieve an entire string,
442\constant{getstr()}. It isn't used very often, because its
443functionality is quite limited; the only editing keys available are
444the backspace key and the Enter key, which terminates the string. It
445can optionally be limited to a fixed number of characters.
446
447\begin{verbatim}
448curses.echo() # Enable echoing of characters
449
450# Get a 15-character string, with the cursor on the top line
451s = stdscr.getstr(0,0, 15)
452\end{verbatim}
453
454The Python \module{curses.textpad} module supplies something better.
455With it, you can turn a window into a text box that supports an
456Emacs-like set of keybindings. Various methods of \class{Textbox}
457class support editing with input validation and gathering the edit
458results either with or without trailing spaces. See the library
459documentation on \module{curses.textpad} for the details.
460
461\section{For More Information}
462
463This HOWTO didn't cover some advanced topics, such as screen-scraping
464or capturing mouse events from an xterm instance. But the Python
465library page for the curses modules is now pretty complete. You
466should browse it next.
467
468If you're in doubt about the detailed behavior of any of the ncurses
469entry points, consult the manual pages for your curses implementation,
470whether it's ncurses or a proprietary Unix vendor's. The manual pages
471will document any quirks, and provide complete lists of all the
472functions, attributes, and \constant{ACS_*} characters available to
473you.
474
475Because the curses API is so large, some functions aren't supported in
476the Python interface, not because they're difficult to implement, but
477because no one has needed them yet. Feel free to add them and then
478submit a patch. Also, we don't yet have support for the menus or
479panels libraries associated with ncurses; feel free to add that.
480
481If you write an interesting little program, feel free to contribute it
482as another demo. We can always use more of them!
483
484The ncurses FAQ: \url{http://dickey.his.com/ncurses/ncurses.faq.html}
485
486\end{document}