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