/Doc/howto/curses.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 436 lines · 343 code · 93 blank · 0 comment · 0 complexity · e8fac361436851892eb8d3eaac62acff MD5 · raw file

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