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