Debian Codegraph @

Doc/howto/curses.rst

raw
1 .. _curses-howto:
2
3 **********************************
4 Curses Programming with Python
5 **********************************
6
7 .. currentmodule:: curses
8
9 :Author: A.M. Kuchling, Eric S. Raymond
10 :Release: 2.04
11
12
13 .. topic:: Abstract
14
15 This document describes how to use the :mod:`curses` extension
16 module to control text-mode displays.
17
18
19 What is curses?
20 ===============
21
22 The curses library supplies a terminal-independent screen-painting and
23 keyboard-handling facility for text-based terminals; such terminals
24 include VT100s, the Linux console, and the simulated terminal provided
25 by various programs. Display terminals support various control codes
26 to perform common operations such as moving the cursor, scrolling the
27 screen, and erasing areas. Different terminals use widely differing
28 codes, and often have their own minor quirks.
29
30 In a world of graphical displays, one might ask "why bother"? It's
31 true that character-cell display terminals are an obsolete technology,
32 but there are niches in which being able to do fancy things with them
33 are still valuable. One niche is on small-footprint or embedded
34 Unixes that don't run an X server. Another is tools such as OS
35 installers and kernel configurators that may have to run before any
36 graphical support is available.
37
38 The curses library provides fairly basic functionality, providing the
39 programmer with an abstraction of a display containing multiple
40 non-overlapping windows of text. The contents of a window can be
41 changed in various ways---adding text, erasing it, changing its
42 appearance---and the curses library will figure out what control codes
43 need to be sent to the terminal to produce the right output. curses
44 doesn't provide many user-interface concepts such as buttons, checkboxes,
45 or dialogs; if you need such features, consider a user interface library such as
46 :pypi:`Urwid`.
47
48 The curses library was originally written for BSD Unix; the later System V
49 versions of Unix from AT&T added many enhancements and new functions. BSD curses
50 is no longer maintained, having been replaced by ncurses, which is an
51 open-source implementation of the AT&T interface. If you're using an
52 open-source Unix such as Linux or FreeBSD, your system almost certainly uses
53 ncurses. Since most current commercial Unix versions are based on System V
54 code, all the functions described here will probably be available. The older
55 versions of curses carried by some proprietary Unixes may not support
56 everything, though.
57
58 The Windows version of Python doesn't include the :mod:`curses`
59 module. A ported version called :pypi:`UniCurses` is available.
60
61
62 The Python curses module
63 ------------------------
64
65 The Python module is a fairly simple wrapper over the C functions provided by
66 curses; if you're already familiar with curses programming in C, it's really
67 easy to transfer that knowledge to Python. The biggest difference is that the
68 Python interface makes things simpler by merging different C functions such as
69 :c:func:`!addstr`, :c:func:`!mvaddstr`, and :c:func:`!mvwaddstr` into a single
70 :meth:`~curses.window.addstr` method. You'll see this covered in more
71 detail later.
72
73 This HOWTO is an introduction to writing text-mode programs with curses
74 and Python. It doesn't attempt to be a complete guide to the curses API; for
75 that, see the Python library guide's section on ncurses, and the C manual pages
76 for ncurses. It will, however, give you the basic ideas.
77
78
79 Starting and ending a curses application
80 ========================================
81
82 Before doing anything, curses must be initialized. This is done by
83 calling the :func:`~curses.initscr` function, which will determine the
84 terminal type, send any required setup codes to the terminal, and
85 create various internal data structures. If successful,
86 :func:`!initscr` returns a window object representing the entire
87 screen; this is usually called ``stdscr`` after the name of the
88 corresponding C variable. ::
89
90 import curses
91 stdscr = curses.initscr()
92
93 Usually curses applications turn off automatic echoing of keys to the
94 screen, in order to be able to read keys and only display them under
95 certain circumstances. This requires calling the
96 :func:`~curses.noecho` function. ::
97
98 curses.noecho()
99
100 Applications will also commonly need to react to keys instantly,
101 without requiring the Enter key to be pressed; this is called cbreak
102 mode, as opposed to the usual buffered input mode. ::
103
104 curses.cbreak()
105
106 Terminals usually return special keys, such as the cursor keys or navigation
107 keys such as Page Up and Home, as a multibyte escape sequence. While you could
108 write your application to expect such sequences and process them accordingly,
109 curses can do it for you, returning a special value such as
110 :const:`curses.KEY_LEFT`. To get curses to do the job, you'll have to enable
111 keypad mode. ::
112
113 stdscr.keypad(True)
114
115 Terminating a curses application is much easier than starting one. You'll need
116 to call::
117
118 curses.nocbreak()
119 stdscr.keypad(False)
120 curses.echo()
121
122 to reverse the curses-friendly terminal settings. Then call the
123 :func:`~curses.endwin` function to restore the terminal to its original
124 operating mode. ::
125
126 curses.endwin()
127
128 A common problem when debugging a curses application is to get your terminal
129 messed up when the application dies without restoring the terminal to its
130 previous state. In Python this commonly happens when your code is buggy and
131 raises an uncaught exception. Keys are no longer echoed to the screen when
132 you type them, for example, which makes using the shell difficult.
133
134 In Python you can avoid these complications and make debugging much easier by
135 importing the :func:`curses.wrapper` function and using it like this::
136
137 from curses import wrapper
138
139 def main(stdscr):
140 # Clear screen
141 stdscr.clear()
142
143 # This raises ZeroDivisionError when i == 10.
144 for i in range(0, 11):
145 v = i-10
146 stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))
147
148 stdscr.refresh()
149 stdscr.getkey()
150
151 wrapper(main)
152
153 The :func:`~curses.wrapper` function takes a callable object and does the
154 initializations described above, also initializing colors if color
155 support is present. :func:`!wrapper` then runs your provided callable.
156 Once the callable returns, :func:`!wrapper` will restore the original
157 state of the terminal. The callable is called inside a
158 :keyword:`try`...\ :keyword:`except` that catches exceptions, restores
159 the state of the terminal, and then re-raises the exception. Therefore
160 your terminal won't be left in a funny state on exception and you'll be
161 able to read the exception's message and traceback.
162
163
164 Windows and Pads
165 ================
166
167 Windows are the basic abstraction in curses. A window object represents a
168 rectangular area of the screen, and supports methods to display text,
169 erase it, allow the user to input strings, and so forth.
170
171 The ``stdscr`` object returned by the :func:`~curses.initscr` function is a
172 window object that covers the entire screen. Many programs may need
173 only this single window, but you might wish to divide the screen into
174 smaller windows, in order to redraw or clear them separately. The
175 :func:`~curses.newwin` function creates a new window of a given size,
176 returning the new window object. ::
177
178 begin_x = 20; begin_y = 7
179 height = 5; width = 40
180 win = curses.newwin(height, width, begin_y, begin_x)
181
182 Note that the coordinate system used in curses is unusual.
183 Coordinates are always passed in the order *y,x*, and the top-left
184 corner of a window is coordinate (0,0). This breaks the normal
185 convention for handling coordinates where the *x* coordinate comes
186 first. This is an unfortunate difference from most other computer
187 applications, but it's been part of curses since it was first written,
188 and it's too late to change things now.
189
190 Your application can determine the size of the screen by using the
191 :data:`curses.LINES` and :data:`curses.COLS` variables to obtain the *y* and
192 *x* sizes. Legal coordinates will then extend from ``(0,0)`` to
193 ``(curses.LINES - 1, curses.COLS - 1)``.
194
195 When you call a method to display or erase text, the effect doesn't
196 immediately show up on the display. Instead you must call the
197 :meth:`~curses.window.refresh` method of window objects to update the
198 screen.
199
200 This is because curses was originally written with slow 300-baud
201 terminal connections in mind; with these terminals, minimizing the
202 time required to redraw the screen was very important. Instead curses
203 accumulates changes to the screen and displays them in the most
204 efficient manner when you call :meth:`!refresh`. For example, if your
205 program displays some text in a window and then clears the window,
206 there's no need to send the original text because they're never
207 visible.
208
209 In practice, explicitly telling curses to redraw a window doesn't
210 really complicate programming with curses much. Most programs go into a flurry
211 of activity, and then pause waiting for a keypress or some other action on the
212 part of the user. All you have to do is to be sure that the screen has been
213 redrawn before pausing to wait for user input, by first calling
214 :meth:`!stdscr.refresh` or the :meth:`!refresh` method of some other relevant
215 window.
216
217 A pad is a special case of a window; it can be larger than the actual display
218 screen, and only a portion of the pad displayed at a time. Creating a pad
219 requires the pad's height and width, while refreshing a pad requires giving the
220 coordinates of the on-screen area where a subsection of the pad will be
221 displayed. ::
222
223 pad = curses.newpad(100, 100)
224 # These loops fill the pad with letters; addch() is
225 # explained in the next section
226 for y in range(0, 99):
227 for x in range(0, 99):
228 pad.addch(y,x, ord('a') + (x*x+y*y) % 26)
229
230 # Displays a section of the pad in the middle of the screen.
231 # (0,0) : coordinate of upper-left corner of pad area to display.
232 # (5,5) : coordinate of upper-left corner of window area to be filled
233 # with pad content.
234 # (20, 75) : coordinate of lower-right corner of window area to be
235 # : filled with pad content.
236 pad.refresh( 0,0, 5,5, 20,75)
237
238 The :meth:`!refresh` call displays a section of the pad in the rectangle
239 extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper
240 left corner of the displayed section is coordinate (0,0) on the pad. Beyond
241 that difference, pads are exactly like ordinary windows and support the same
242 methods.
243
244 If you have multiple windows and pads on screen there is a more
245 efficient way to update the screen and prevent annoying screen flicker
246 as each part of the screen gets updated. :meth:`!refresh` actually
247 does two things:
248
249 1) Calls the :meth:`~curses.window.noutrefresh` method of each window
250 to update an underlying data structure representing the desired
251 state of the screen.
252 2) Calls the function :func:`~curses.doupdate` function to change the
253 physical screen to match the desired state recorded in the data structure.
254
255 Instead you can call :meth:`!noutrefresh` on a number of windows to
256 update the data structure, and then call :func:`!doupdate` to update
257 the screen.
258
259
260 Displaying Text
261 ===============
262
263 From a C programmer's point of view, curses may sometimes look like a
264 twisty maze of functions, all subtly different. For example,
265 :c:func:`!addstr` displays a string at the current cursor location in
266 the ``stdscr`` window, while :c:func:`!mvaddstr` moves to a given y,x
267 coordinate first before displaying the string. :c:func:`!waddstr` is just
268 like :c:func:`!addstr`, but allows specifying a window to use instead of
269 using ``stdscr`` by default. :c:func:`!mvwaddstr` allows specifying both
270 a window and a coordinate.
271
272 Fortunately the Python interface hides all these details. ``stdscr``
273 is a window object like any other, and methods such as
274 :meth:`~curses.window.addstr` accept multiple argument forms. Usually there
275 are four different forms.
276
277 +---------------------------------+-----------------------------------------------+
278 | Form | Description |
279 +=================================+===============================================+
280 | *str* or *ch* | Display the string *str* or character *ch* at |
281 | | the current position |
282 +---------------------------------+-----------------------------------------------+
283 | *str* or *ch*, *attr* | Display the string *str* or character *ch*, |
284 | | using attribute *attr* at the current |
285 | | position |
286 +---------------------------------+-----------------------------------------------+
287 | *y*, *x*, *str* or *ch* | Move to position *y,x* within the window, and |
288 | | display *str* or *ch* |
289 +---------------------------------+-----------------------------------------------+
290 | *y*, *x*, *str* or *ch*, *attr* | Move to position *y,x* within the window, and |
291 | | display *str* or *ch*, using attribute *attr* |
292 +---------------------------------+-----------------------------------------------+
293
294 Attributes allow displaying text in highlighted forms such as boldface,
295 underline, reverse code, or in color. They'll be explained in more detail in
296 the next subsection.
297
298
299 The :meth:`~curses.window.addstr` method takes a Python string or
300 bytestring as the value to be displayed. The contents of bytestrings
301 are sent to the terminal as-is. Strings are encoded to bytes using
302 the value of the window's :attr:`~window.encoding` attribute; this defaults to
303 the default system encoding as returned by :func:`locale.getencoding`.
304
305 The :meth:`~curses.window.addch` methods take a character, which can be
306 either a string of length 1, a bytestring of length 1, or an integer.
307
308 Constants are provided for extension characters; these constants are
309 integers greater than 255. For example, :const:`ACS_PLMINUS` is a +/-
310 symbol, and :const:`ACS_ULCORNER` is the upper left corner of a box
311 (handy for drawing borders). You can also use the appropriate Unicode
312 character.
313
314 Windows remember where the cursor was left after the last operation, so if you
315 leave out the *y,x* coordinates, the string or character will be displayed
316 wherever the last operation left off. You can also move the cursor with the
317 ``move(y,x)`` method. Because some terminals always display a flashing cursor,
318 you may want to ensure that the cursor is positioned in some location where it
319 won't be distracting; it can be confusing to have the cursor blinking at some
320 apparently random location.
321
322 If your application doesn't need a blinking cursor at all, you can
323 call ``curs_set(False)`` to make it invisible. For compatibility
324 with older curses versions, there's a ``leaveok(bool)`` function
325 that's a synonym for :func:`~curses.curs_set`. When *bool* is true, the
326 curses library will attempt to suppress the flashing cursor, and you
327 won't need to worry about leaving it in odd locations.
328
329
330 Attributes and Color
331 --------------------
332
333 Characters can be displayed in different ways. Status lines in a text-based
334 application are commonly shown in reverse video, or a text viewer may need to
335 highlight certain words. curses supports this by allowing you to specify an
336 attribute for each cell on the screen.
337
338 An attribute is an integer, each bit representing a different
339 attribute. You can try to display text with multiple attribute bits
340 set, but curses doesn't guarantee that all the possible combinations
341 are available, or that they're all visually distinct. That depends on
342 the ability of the terminal being used, so it's safest to stick to the
343 most commonly available attributes, listed here.
344
345 +----------------------+--------------------------------------+
346 | Attribute | Description |
347 +======================+======================================+
348 | :const:`A_BLINK` | Blinking text |
349 +----------------------+--------------------------------------+
350 | :const:`A_BOLD` | Extra bright or bold text |
351 +----------------------+--------------------------------------+
352 | :const:`A_DIM` | Half bright text |
353 +----------------------+--------------------------------------+
354 | :const:`A_REVERSE` | Reverse-video text |
355 +----------------------+--------------------------------------+
356 | :const:`A_STANDOUT` | The best highlighting mode available |
357 +----------------------+--------------------------------------+
358 | :const:`A_UNDERLINE` | Underlined text |
359 +----------------------+--------------------------------------+
360
361 So, to display a reverse-video status line on the top line of the screen, you
362 could code::
363
364 stdscr.addstr(0, 0, "Current mode: Typing mode",
365 curses.A_REVERSE)
366 stdscr.refresh()
367
368 The curses library also supports color on those terminals that provide it. The
369 most common such terminal is probably the Linux console, followed by color
370 xterms.
371
372 To use color, you must call the :func:`~curses.start_color` function soon
373 after calling :func:`~curses.initscr`, to initialize the default color set
374 (the :func:`curses.wrapper` function does this automatically). Once that's
375 done, the :func:`~curses.has_colors` function returns TRUE if the terminal
376 in use can
377 actually display color. (Note: curses uses the American spelling 'color',
378 instead of the Canadian/British spelling 'colour'. If you're used to the
379 British spelling, you'll have to resign yourself to misspelling it for the sake
380 of these functions.)
381
382 The curses library maintains a finite number of color pairs, containing a
383 foreground (or text) color and a background color. You can get the attribute
384 value corresponding to a color pair with the :func:`~curses.color_pair`
385 function; this can be bitwise-OR'ed with other attributes such as
386 :const:`A_REVERSE`, but again, such combinations are not guaranteed to work
387 on all terminals.
388
389 An example, which displays a line of text using color pair 1::
390
391 stdscr.addstr("Pretty text", curses.color_pair(1))
392 stdscr.refresh()
393
394 As I said before, a color pair consists of a foreground and background color.
395 The ``init_pair(n, f, b)`` function changes the definition of color pair *n*, to
396 foreground color f and background color b. Color pair 0 is hard-wired to white
397 on black, and cannot be changed.
398
399 Colors are numbered, and :func:`start_color` initializes 8 basic
400 colors when it activates color mode. They are: 0:black, 1:red,
401 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The :mod:`curses`
402 module defines named constants for each of these colors:
403 :const:`curses.COLOR_BLACK`, :const:`curses.COLOR_RED`, and so forth.
404
405 Let's put all this together. To change color 1 to red text on a white
406 background, you would call::
407
408 curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
409
410 When you change a color pair, any text already displayed using that color pair
411 will change to the new colors. You can also display new text in this color
412 with::
413
414 stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))
415
416 Very fancy terminals can change the definitions of the actual colors to a given
417 RGB value. This lets you change color 1, which is usually red, to purple or
418 blue or any other color you like. Unfortunately, the Linux console doesn't
419 support this, so I'm unable to try it out, and can't provide any examples. You
420 can check if your terminal can do this by calling
421 :func:`~curses.can_change_color`, which returns ``True`` if the capability is
422 there. If you're lucky enough to have such a talented terminal, consult your
423 system's man pages for more information.
424
425
426 User Input
427 ==========
428
429 The C curses library offers only very simple input mechanisms. Python's
430 :mod:`curses` module adds a basic text-input widget. (Other libraries
431 such as :pypi:`Urwid` have more extensive collections of widgets.)
432
433 There are two methods for getting input from a window:
434
435 * :meth:`~curses.window.getch` refreshes the screen and then waits for
436 the user to hit a key, displaying the key if :func:`~curses.echo` has been
437 called earlier. You can optionally specify a coordinate to which
438 the cursor should be moved before pausing.
439
440 * :meth:`~curses.window.getkey` does the same thing but converts the
441 integer to a string. Individual characters are returned as
442 1-character strings, and special keys such as function keys return
443 longer strings containing a key name such as ``KEY_UP`` or ``^G``.
444
445 It's possible to not wait for the user using the
446 :meth:`~curses.window.nodelay` window method. After ``nodelay(True)``,
447 :meth:`!getch` and :meth:`!getkey` for the window become
448 non-blocking. To signal that no input is ready, :meth:`!getch` returns
449 ``curses.ERR`` (a value of -1) and :meth:`!getkey` raises an exception.
450 There's also a :func:`~curses.halfdelay` function, which can be used to (in
451 effect) set a timer on each :meth:`!getch`; if no input becomes
452 available within a specified delay (measured in tenths of a second),
453 curses raises an exception.
454
455 The :meth:`!getch` method returns an integer; if it's between 0 and 255, it
456 represents the ASCII code of the key pressed. Values greater than 255 are
457 special keys such as Page Up, Home, or the cursor keys. You can compare the
458 value returned to constants such as :const:`curses.KEY_PPAGE`,
459 :const:`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. The main loop of
460 your program may look something like this::
461
462 while True:
463 c = stdscr.getch()
464 if c == ord('p'):
465 PrintDocument()
466 elif c == ord('q'):
467 break # Exit the while loop
468 elif c == curses.KEY_HOME:
469 x = y = 0
470
471 The :mod:`curses.ascii` module supplies ASCII class membership functions that
472 take either integer or 1-character string arguments; these may be useful in
473 writing more readable tests for such loops. It also supplies
474 conversion functions that take either integer or 1-character-string arguments
475 and return the same type. For example, :func:`curses.ascii.ctrl` returns the
476 control character corresponding to its argument.
477
478 There's also a method to retrieve an entire string,
479 :meth:`~curses.window.getstr`. It isn't used very often, because its
480 functionality is quite limited; the only editing keys available are
481 the backspace key and the Enter key, which terminates the string. It
482 can optionally be limited to a fixed number of characters. ::
483
484 curses.echo() # Enable echoing of characters
485
486 # Get a 15-character string, with the cursor on the top line
487 s = stdscr.getstr(0,0, 15)
488
489 The :mod:`curses.textpad` module supplies a text box that supports an
490 Emacs-like set of keybindings. Various methods of the
491 :class:`~curses.textpad.Textbox` class support editing with input
492 validation and gathering the edit results either with or without
493 trailing spaces. Here's an example::
494
495 import curses
496 from curses.textpad import Textbox, rectangle
497
498 def main(stdscr):
499 stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")
500
501 editwin = curses.newwin(5,30, 2,1)
502 rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
503 stdscr.refresh()
504
505 box = Textbox(editwin)
506
507 # Let the user edit until Ctrl-G is struck.
508 box.edit()
509
510 # Get resulting contents
511 message = box.gather()
512
513 See the library documentation on :mod:`curses.textpad` for more details.
514
515
516 For More Information
517 ====================
518
519 This HOWTO doesn't cover some advanced topics, such as reading the
520 contents of the screen or capturing mouse events from an xterm
521 instance, but the Python library page for the :mod:`curses` module is now
522 reasonably complete. You should browse it next.
523
524 If you're in doubt about the detailed behavior of the curses
525 functions, consult the manual pages for your curses implementation,
526 whether it's ncurses or a proprietary Unix vendor's. The manual pages
527 will document any quirks, and provide complete lists of all the
528 functions, attributes, and :ref:`ACS_\* <curses-acs-codes>` characters available to
529 you.
530
531 Because the curses API is so large, some functions aren't supported in
532 the Python interface. Often this isn't because they're difficult to
533 implement, but because no one has needed them yet. Also, Python
534 doesn't yet support the menu library associated with ncurses.
535 Patches adding support for these would be welcome; see
536 `the Python Developer's Guide <https://devguide.python.org/>`_ to
537 learn more about submitting patches to Python.
538
539 * `Writing Programs with NCURSES <https://invisible-island.net/ncurses/ncurses-intro.html>`_:
540 a lengthy tutorial for C programmers.
541 * `The ncurses man page <https://linux.die.net/man/3/ncurses>`_
542 * `The ncurses FAQ <https://invisible-island.net/ncurses/ncurses.faq.html>`_
543 * `"Use curses... don't swear" <https://www.youtube.com/watch?v=eN1eZtjLEnU>`_:
544 video of a PyCon 2013 talk on controlling terminals using curses or Urwid.
545 * `"Console Applications with Urwid" <https://pyvideo.org/video/1568/console-applications-with-urwid>`_:
546 video of a PyCon CA 2012 talk demonstrating some applications written using
547 Urwid.