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