Curses Programming with Python

作者:

A.M. Kuchling, Eric S. Raymond

發佈版本:

2.04

摘要

This document describes how to use thecurses extensionmodule to control text-mode displays.

What is curses?

The curses library supplies a terminal-independent screen-painting andkeyboard-handling facility for text-based terminals; such terminalsinclude VT100s, the Linux console, and the simulated terminal providedby various programs. Display terminals support various control codesto perform common operations such as moving the cursor, scrolling thescreen, and erasing areas. Different terminals use widely differingcodes, and often have their own minor quirks.

In a world of graphical displays, one might ask "why bother"? It'strue that character-cell display terminals are an obsolete technology,but there are niches in which being able to do fancy things with themare still valuable. One niche is on small-footprint or embeddedUnixes that don't run an X server. Another is tools such as OSinstallers and kernel configurators that may have to run before anygraphical support is available.

The curses library provides fairly basic functionality, providing theprogrammer with an abstraction of a display containing multiplenon-overlapping windows of text. The contents of a window can bechanged in various ways---adding text, erasing it, changing itsappearance---and the curses library will figure out what control codesneed to be sent to the terminal to produce the right output. cursesdoesn't provide many user-interface concepts such as buttons, checkboxes,or dialogs; if you need such features, consider a user interface library such asUrwid.

The curses library was originally written for BSD Unix; the later System Vversions of Unix from AT&T added many enhancements and new functions. BSD cursesis no longer maintained, having been replaced by ncurses, which is anopen-source implementation of the AT&T interface. If you're using anopen-source Unix such as Linux or FreeBSD, your system almost certainly usesncurses. Since most current commercial Unix versions are based on System Vcode, all the functions described here will probably be available. The olderversions of curses carried by some proprietary Unixes may not supporteverything, though.

The Windows version of Python doesn't include thecursesmodule. A ported version calledUniCurses is available.

Python curses 模組

The Python module is a fairly simple wrapper over the C functions provided bycurses; if you're already familiar with curses programming in C, it's reallyeasy to transfer that knowledge to Python. The biggest difference is that thePython interface makes things simpler by merging different C functions such asaddstr(),mvaddstr(), andmvwaddstr() into a singleaddstr() method. You'll see this covered in moredetail later.

This HOWTO is an introduction to writing text-mode programs with cursesand Python. It doesn't attempt to be a complete guide to the curses API; forthat, see the Python library guide's section on ncurses, and the C manual pagesfor ncurses. It will, however, give you the basic ideas.

Starting and ending a curses application

Before doing anything, curses must be initialized. This is done bycalling theinitscr() function, which will determine theterminal type, send any required setup codes to the terminal, andcreate various internal data structures. If successful,initscr() returns a window object representing the entirescreen; this is usually calledstdscr after the name of thecorresponding C variable.

importcursesstdscr=curses.initscr()

Usually curses applications turn off automatic echoing of keys to thescreen, in order to be able to read keys and only display them undercertain circumstances. This requires calling thenoecho() function.

curses.noecho()

Applications will also commonly need to react to keys instantly,without requiring the Enter key to be pressed; this is called cbreakmode, as opposed to the usual buffered input mode.

curses.cbreak()

Terminals usually return special keys, such as the cursor keys or navigationkeys such as Page Up and Home, as a multibyte escape sequence. While you couldwrite your application to expect such sequences and process them accordingly,curses can do it for you, returning a special value such ascurses.KEY_LEFT. To get curses to do the job, you'll have to enablekeypad mode.

stdscr.keypad(True)

Terminating a curses application is much easier than starting one. You'll needto call:

curses.nocbreak()stdscr.keypad(False)curses.echo()

to reverse the curses-friendly terminal settings. Then call theendwin() function to restore the terminal to its originaloperating mode.

curses.endwin()

A common problem when debugging a curses application is to get your terminalmessed up when the application dies without restoring the terminal to itsprevious state. In Python this commonly happens when your code is buggy andraises an uncaught exception. Keys are no longer echoed to the screen whenyou type them, for example, which makes using the shell difficult.

In Python you can avoid these complications and make debugging much easier byimporting thecurses.wrapper() function and using it like this:

fromcursesimportwrapperdefmain(stdscr):# Clear screenstdscr.clear()# This raises ZeroDivisionError when i == 10.foriinrange(0,11):v=i-10stdscr.addstr(i,0,'10 divided by{} is{}'.format(v,10/v))stdscr.refresh()stdscr.getkey()wrapper(main)

Thewrapper() function takes a callable object and does theinitializations described above, also initializing colors if colorsupport is present.wrapper() then runs your provided callable.Once the callable returns,wrapper() will restore the originalstate of the terminal. The callable is called inside atry...except that catches exceptions, restoresthe state of the terminal, and then re-raises the exception. Thereforeyour terminal won't be left in a funny state on exception and you'll beable to read the exception's message and traceback.

Windows and Pads

Windows are the basic abstraction in curses. A window object represents arectangular area of the screen, and supports methods to display text,erase it, allow the user to input strings, and so forth.

Thestdscr object returned by theinitscr() function is awindow object that covers the entire screen. Many programs may needonly this single window, but you might wish to divide the screen intosmaller windows, in order to redraw or clear them separately. Thenewwin() function creates a new window of a given size,returning the new window object.

begin_x=20;begin_y=7height=5;width=40win=curses.newwin(height,width,begin_y,begin_x)

Note that the coordinate system used in curses is unusual.Coordinates are always passed in the ordery,x, and the top-leftcorner of a window is coordinate (0,0). This breaks the normalconvention for handling coordinates where thex coordinate comesfirst. This is an unfortunate difference from most other computerapplications, but it's been part of curses since it was first written,and it's too late to change things now.

Your application can determine the size of the screen by using thecurses.LINES andcurses.COLS variables to obtain they andx sizes. Legal coordinates will then extend from(0,0) to(curses.LINES-1,curses.COLS-1).

When you call a method to display or erase text, the effect doesn'timmediately show up on the display. Instead you must call therefresh() method of window objects to update thescreen.

This is because curses was originally written with slow 300-baudterminal connections in mind; with these terminals, minimizing thetime required to redraw the screen was very important. Instead cursesaccumulates changes to the screen and displays them in the mostefficient manner when you callrefresh(). For example, if yourprogram displays some text in a window and then clears the window,there's no need to send the original text because they're nevervisible.

In practice, explicitly telling curses to redraw a window doesn'treally complicate programming with curses much. Most programs go into a flurryof activity, and then pause waiting for a keypress or some other action on thepart of the user. All you have to do is to be sure that the screen has beenredrawn before pausing to wait for user input, by first callingstdscr.refresh() or therefresh() method of some other relevantwindow.

A pad is a special case of a window; it can be larger than the actual displayscreen, and only a portion of the pad displayed at a time. Creating a padrequires the pad's height and width, while refreshing a pad requires giving thecoordinates of the on-screen area where a subsection of the pad will bedisplayed.

pad=curses.newpad(100,100)# These loops fill the pad with letters; addch() is# explained in the next sectionforyinrange(0,99):forxinrange(0,99):pad.addch(y,x,ord('a')+(x*x+y*y)%26)# Displays a section of the pad in the middle of the screen.# (0,0) : coordinate of upper-left corner of pad area to display.# (5,5) : coordinate of upper-left corner of window area to be filled#         with pad content.# (20, 75) : coordinate of lower-right corner of window area to be#          : filled with pad content.pad.refresh(0,0,5,5,20,75)

Therefresh() call displays a section of the pad in the rectangleextending from coordinate (5,5) to coordinate (20,75) on the screen; the upperleft corner of the displayed section is coordinate (0,0) on the pad. Beyondthat difference, pads are exactly like ordinary windows and support the samemethods.

If you have multiple windows and pads on screen there is a moreefficient way to update the screen and prevent annoying screen flickeras each part of the screen gets updated.refresh() actuallydoes two things:

  1. Calls thenoutrefresh() method of each windowto update an underlying data structure representing the desiredstate of the screen.

  2. Calls the functiondoupdate() function to change thephysical screen to match the desired state recorded in the data structure.

Instead you can callnoutrefresh() on a number of windows toupdate the data structure, and then calldoupdate() to updatethe screen.

Displaying Text

From a C programmer's point of view, curses may sometimes look like atwisty maze of functions, all subtly different. For example,addstr() displays a string at the current cursor location inthestdscr window, whilemvaddstr() moves to a given y,xcoordinate first before displaying the string.waddstr() is justlikeaddstr(), but allows specifying a window to use instead ofusingstdscr by default.mvwaddstr() allows specifying botha window and a coordinate.

Fortunately the Python interface hides all these details.stdscris a window object like any other, and methods such asaddstr() accept multiple argument forms. Usually thereare four different forms.

Form

描述

strch

Display the stringstr or characterch atthe current position

str orch,attr

Display the stringstr or characterch,using attributeattr at the currentposition

yxstrch

Move to positiony,x within the window, anddisplaystr orch

yxstrchattr

Move to positiony,x within the window, anddisplaystr orch, using attributeattr

Attributes allow displaying text in highlighted forms such as boldface,underline, reverse code, or in color. They'll be explained in more detail inthe next subsection.

Theaddstr() method takes a Python string orbytestring as the value to be displayed. The contents of bytestringsare sent to the terminal as-is. Strings are encoded to bytes usingthe value of the window'sencoding attribute; this defaults tothe default system encoding as returned bylocale.getencoding().

Theaddch() methods take a character, which can beeither a string of length 1, a bytestring of length 1, or an integer.

Constants are provided for extension characters; these constants areintegers greater than 255. For example,ACS_PLMINUS is a +/-symbol, andACS_ULCORNER is the upper left corner of a box(handy for drawing borders). You can also use the appropriate Unicodecharacter.

Windows remember where the cursor was left after the last operation, so if youleave out they,x coordinates, the string or character will be displayedwherever the last operation left off. You can also move the cursor with themove(y,x) method. Because some terminals always display a flashing cursor,you may want to ensure that the cursor is positioned in some location where itwon't be distracting; it can be confusing to have the cursor blinking at someapparently random location.

If your application doesn't need a blinking cursor at all, you cancallcurs_set(False) to make it invisible. For compatibilitywith older curses versions, there's aleaveok(bool) functionthat's a synonym forcurs_set(). Whenbool is true, thecurses library will attempt to suppress the flashing cursor, and youwon't need to worry about leaving it in odd locations.

Attributes and Color

Characters can be displayed in different ways. Status lines in a text-basedapplication are commonly shown in reverse video, or a text viewer may need tohighlight certain words. curses supports this by allowing you to specify anattribute for each cell on the screen.

An attribute is an integer, each bit representing a differentattribute. You can try to display text with multiple attribute bitsset, but curses doesn't guarantee that all the possible combinationsare available, or that they're all visually distinct. That depends onthe ability of the terminal being used, so it's safest to stick to themost commonly available attributes, listed here.

屬性

描述

A_BLINK

Blinking text

A_BOLD

Extra bright or bold text

A_DIM

Half bright text

A_REVERSE

Reverse-video text

A_STANDOUT

The best highlighting mode available

A_UNDERLINE

Underlined text

So, to display a reverse-video status line on the top line of the screen, youcould code:

stdscr.addstr(0,0,"Current mode: Typing mode",curses.A_REVERSE)stdscr.refresh()

The curses library also supports color on those terminals that provide it. Themost common such terminal is probably the Linux console, followed by colorxterms.

To use color, you must call thestart_color() function soonafter callinginitscr(), to initialize the default color set(thecurses.wrapper() function does this automatically). Once that'sdone, thehas_colors() function returns TRUE if the terminalin use canactually display color. (Note: curses uses the American spelling 'color',instead of the Canadian/British spelling 'colour'. If you're used to theBritish spelling, you'll have to resign yourself to misspelling it for the sakeof these functions.)

The curses library maintains a finite number of color pairs, containing aforeground (or text) color and a background color. You can get the attributevalue corresponding to a color pair with thecolor_pair()function; this can be bitwise-OR'ed with other attributes such asA_REVERSE, but again, such combinations are not guaranteed to workon all terminals.

An example, which displays a line of text using color pair 1:

stdscr.addstr("Pretty text",curses.color_pair(1))stdscr.refresh()

As I said before, a color pair consists of a foreground and background color.Theinit_pair(n,f,b) function changes the definition of color pairn, toforeground color f and background color b. Color pair 0 is hard-wired to whiteon black, and cannot be changed.

Colors are numbered, andstart_color() initializes 8 basiccolors when it activates color mode. They are: 0:black, 1:red,2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. Thecursesmodule defines named constants for each of these colors:curses.COLOR_BLACK,curses.COLOR_RED, and so forth.

Let's put all this together. To change color 1 to red text on a whitebackground, you would call:

curses.init_pair(1,curses.COLOR_RED,curses.COLOR_WHITE)

When you change a color pair, any text already displayed using that color pairwill change to the new colors. You can also display new text in this colorwith:

stdscr.addstr(0,0,"RED ALERT!",curses.color_pair(1))

Very fancy terminals can change the definitions of the actual colors to a givenRGB value. This lets you change color 1, which is usually red, to purple orblue or any other color you like. Unfortunately, the Linux console doesn'tsupport this, so I'm unable to try it out, and can't provide any examples. Youcan check if your terminal can do this by callingcan_change_color(), which returnsTrue if the capability isthere. If you're lucky enough to have such a talented terminal, consult yoursystem's man pages for more information.

使用者輸入

The C curses library offers only very simple input mechanisms. Python'scurses module adds a basic text-input widget. (Other librariessuch asUrwid have more extensive collections of widgets.)

There are two methods for getting input from a window:

  • getch() refreshes the screen and then waits forthe user to hit a key, displaying the key ifecho() has beencalled earlier. You can optionally specify a coordinate to whichthe cursor should be moved before pausing.

  • getkey() does the same thing but converts theinteger to a string. Individual characters are returned as1-character strings, and special keys such as function keys returnlonger strings containing a key name such asKEY_UP or^G.

It's possible to not wait for the user using thenodelay() window method. Afternodelay(True),getch() andgetkey() for the window becomenon-blocking. To signal that no input is ready,getch() returnscurses.ERR (a value of -1) andgetkey() raises an exception.There's also ahalfdelay() function, which can be used to (ineffect) set a timer on eachgetch(); if no input becomesavailable within a specified delay (measured in tenths of a second),curses raises an exception.

Thegetch() method returns an integer; if it's between 0 and 255, itrepresents the ASCII code of the key pressed. Values greater than 255 arespecial keys such as Page Up, Home, or the cursor keys. You can compare thevalue returned to constants such ascurses.KEY_PPAGE,curses.KEY_HOME, orcurses.KEY_LEFT. The main loop ofyour program may look something like this:

whileTrue:c=stdscr.getch()ifc==ord('p'):PrintDocument()elifc==ord('q'):break# Exit the while loopelifc==curses.KEY_HOME:x=y=0

Thecurses.ascii module supplies ASCII class membership functions thattake either integer or 1-character string arguments; these may be useful inwriting more readable tests for such loops. It also suppliesconversion functions that take either integer or 1-character-string argumentsand return the same type. For example,curses.ascii.ctrl() returns thecontrol character corresponding to its argument.

There's also a method to retrieve an entire string,getstr(). It isn't used very often, because itsfunctionality is quite limited; the only editing keys available arethe backspace key and the Enter key, which terminates the string. Itcan optionally be limited to a fixed number of characters.

curses.echo()# Enable echoing of characters# Get a 15-character string, with the cursor on the top lines=stdscr.getstr(0,0,15)

Thecurses.textpad module supplies a text box that supports anEmacs-like set of keybindings. Various methods of theTextbox class support editing with inputvalidation and gathering the edit results either with or withouttrailing spaces. Here's an example:

importcursesfromcurses.textpadimportTextbox,rectangledefmain(stdscr):stdscr.addstr(0,0,"Enter IM message: (hit Ctrl-G to send)")editwin=curses.newwin(5,30,2,1)rectangle(stdscr,1,0,1+5+1,1+30+1)stdscr.refresh()box=Textbox(editwin)# Let the user edit until Ctrl-G is struck.box.edit()# Get resulting contentsmessage=box.gather()

See the library documentation oncurses.textpad for more details.

For More Information

This HOWTO doesn't cover some advanced topics, such as reading thecontents of the screen or capturing mouse events from an xterminstance, but the Python library page for thecurses module is nowreasonably complete. You should browse it next.

If you're in doubt about the detailed behavior of the cursesfunctions, consult the manual pages for your curses implementation,whether it's ncurses or a proprietary Unix vendor's. The manual pageswill document any quirks, and provide complete lists of all thefunctions, attributes, andACS_* characters available toyou.

Because the curses API is so large, some functions aren't supported inthe Python interface. Often this isn't because they're difficult toimplement, but because no one has needed them yet. Also, Pythondoesn't yet support the menu library associated with ncurses.Patches adding support for these would be welcome; seethe Python Developer's Guide tolearn more about submitting patches to Python.