17db96d56Sopenharmony_ci.. _curses-howto: 27db96d56Sopenharmony_ci 37db96d56Sopenharmony_ci********************************** 47db96d56Sopenharmony_ci Curses Programming with Python 57db96d56Sopenharmony_ci********************************** 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci.. currentmodule:: curses 87db96d56Sopenharmony_ci 97db96d56Sopenharmony_ci:Author: A.M. Kuchling, Eric S. Raymond 107db96d56Sopenharmony_ci:Release: 2.04 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci 137db96d56Sopenharmony_ci.. topic:: Abstract 147db96d56Sopenharmony_ci 157db96d56Sopenharmony_ci This document describes how to use the :mod:`curses` extension 167db96d56Sopenharmony_ci module to control text-mode displays. 177db96d56Sopenharmony_ci 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciWhat is curses? 207db96d56Sopenharmony_ci=============== 217db96d56Sopenharmony_ci 227db96d56Sopenharmony_ciThe curses library supplies a terminal-independent screen-painting and 237db96d56Sopenharmony_cikeyboard-handling facility for text-based terminals; such terminals 247db96d56Sopenharmony_ciinclude VT100s, the Linux console, and the simulated terminal provided 257db96d56Sopenharmony_ciby various programs. Display terminals support various control codes 267db96d56Sopenharmony_cito perform common operations such as moving the cursor, scrolling the 277db96d56Sopenharmony_ciscreen, and erasing areas. Different terminals use widely differing 287db96d56Sopenharmony_cicodes, and often have their own minor quirks. 297db96d56Sopenharmony_ci 307db96d56Sopenharmony_ciIn a world of graphical displays, one might ask "why bother"? It's 317db96d56Sopenharmony_citrue that character-cell display terminals are an obsolete technology, 327db96d56Sopenharmony_cibut there are niches in which being able to do fancy things with them 337db96d56Sopenharmony_ciare still valuable. One niche is on small-footprint or embedded 347db96d56Sopenharmony_ciUnixes that don't run an X server. Another is tools such as OS 357db96d56Sopenharmony_ciinstallers and kernel configurators that may have to run before any 367db96d56Sopenharmony_cigraphical support is available. 377db96d56Sopenharmony_ci 387db96d56Sopenharmony_ciThe curses library provides fairly basic functionality, providing the 397db96d56Sopenharmony_ciprogrammer with an abstraction of a display containing multiple 407db96d56Sopenharmony_cinon-overlapping windows of text. The contents of a window can be 417db96d56Sopenharmony_cichanged in various ways---adding text, erasing it, changing its 427db96d56Sopenharmony_ciappearance---and the curses library will figure out what control codes 437db96d56Sopenharmony_cineed to be sent to the terminal to produce the right output. curses 447db96d56Sopenharmony_cidoesn't provide many user-interface concepts such as buttons, checkboxes, 457db96d56Sopenharmony_cior dialogs; if you need such features, consider a user interface library such as 467db96d56Sopenharmony_ci`Urwid <https://pypi.org/project/urwid/>`_. 477db96d56Sopenharmony_ci 487db96d56Sopenharmony_ciThe curses library was originally written for BSD Unix; the later System V 497db96d56Sopenharmony_civersions of Unix from AT&T added many enhancements and new functions. BSD curses 507db96d56Sopenharmony_ciis no longer maintained, having been replaced by ncurses, which is an 517db96d56Sopenharmony_ciopen-source implementation of the AT&T interface. If you're using an 527db96d56Sopenharmony_ciopen-source Unix such as Linux or FreeBSD, your system almost certainly uses 537db96d56Sopenharmony_cincurses. Since most current commercial Unix versions are based on System V 547db96d56Sopenharmony_cicode, all the functions described here will probably be available. The older 557db96d56Sopenharmony_civersions of curses carried by some proprietary Unixes may not support 567db96d56Sopenharmony_cieverything, though. 577db96d56Sopenharmony_ci 587db96d56Sopenharmony_ciThe Windows version of Python doesn't include the :mod:`curses` 597db96d56Sopenharmony_cimodule. A ported version called `UniCurses 607db96d56Sopenharmony_ci<https://pypi.org/project/UniCurses>`_ is available. 617db96d56Sopenharmony_ci 627db96d56Sopenharmony_ci 637db96d56Sopenharmony_ciThe Python curses module 647db96d56Sopenharmony_ci------------------------ 657db96d56Sopenharmony_ci 667db96d56Sopenharmony_ciThe Python module is a fairly simple wrapper over the C functions provided by 677db96d56Sopenharmony_cicurses; if you're already familiar with curses programming in C, it's really 687db96d56Sopenharmony_cieasy to transfer that knowledge to Python. The biggest difference is that the 697db96d56Sopenharmony_ciPython interface makes things simpler by merging different C functions such as 707db96d56Sopenharmony_ci:c:func:`!addstr`, :c:func:`!mvaddstr`, and :c:func:`!mvwaddstr` into a single 717db96d56Sopenharmony_ci:meth:`~curses.window.addstr` method. You'll see this covered in more 727db96d56Sopenharmony_cidetail later. 737db96d56Sopenharmony_ci 747db96d56Sopenharmony_ciThis HOWTO is an introduction to writing text-mode programs with curses 757db96d56Sopenharmony_ciand Python. It doesn't attempt to be a complete guide to the curses API; for 767db96d56Sopenharmony_cithat, see the Python library guide's section on ncurses, and the C manual pages 777db96d56Sopenharmony_cifor ncurses. It will, however, give you the basic ideas. 787db96d56Sopenharmony_ci 797db96d56Sopenharmony_ci 807db96d56Sopenharmony_ciStarting and ending a curses application 817db96d56Sopenharmony_ci======================================== 827db96d56Sopenharmony_ci 837db96d56Sopenharmony_ciBefore doing anything, curses must be initialized. This is done by 847db96d56Sopenharmony_cicalling the :func:`~curses.initscr` function, which will determine the 857db96d56Sopenharmony_citerminal type, send any required setup codes to the terminal, and 867db96d56Sopenharmony_cicreate various internal data structures. If successful, 877db96d56Sopenharmony_ci:func:`!initscr` returns a window object representing the entire 887db96d56Sopenharmony_ciscreen; this is usually called ``stdscr`` after the name of the 897db96d56Sopenharmony_cicorresponding C variable. :: 907db96d56Sopenharmony_ci 917db96d56Sopenharmony_ci import curses 927db96d56Sopenharmony_ci stdscr = curses.initscr() 937db96d56Sopenharmony_ci 947db96d56Sopenharmony_ciUsually curses applications turn off automatic echoing of keys to the 957db96d56Sopenharmony_ciscreen, in order to be able to read keys and only display them under 967db96d56Sopenharmony_cicertain circumstances. This requires calling the 977db96d56Sopenharmony_ci:func:`~curses.noecho` function. :: 987db96d56Sopenharmony_ci 997db96d56Sopenharmony_ci curses.noecho() 1007db96d56Sopenharmony_ci 1017db96d56Sopenharmony_ciApplications will also commonly need to react to keys instantly, 1027db96d56Sopenharmony_ciwithout requiring the Enter key to be pressed; this is called cbreak 1037db96d56Sopenharmony_cimode, as opposed to the usual buffered input mode. :: 1047db96d56Sopenharmony_ci 1057db96d56Sopenharmony_ci curses.cbreak() 1067db96d56Sopenharmony_ci 1077db96d56Sopenharmony_ciTerminals usually return special keys, such as the cursor keys or navigation 1087db96d56Sopenharmony_cikeys such as Page Up and Home, as a multibyte escape sequence. While you could 1097db96d56Sopenharmony_ciwrite your application to expect such sequences and process them accordingly, 1107db96d56Sopenharmony_cicurses can do it for you, returning a special value such as 1117db96d56Sopenharmony_ci:const:`curses.KEY_LEFT`. To get curses to do the job, you'll have to enable 1127db96d56Sopenharmony_cikeypad mode. :: 1137db96d56Sopenharmony_ci 1147db96d56Sopenharmony_ci stdscr.keypad(True) 1157db96d56Sopenharmony_ci 1167db96d56Sopenharmony_ciTerminating a curses application is much easier than starting one. You'll need 1177db96d56Sopenharmony_cito call:: 1187db96d56Sopenharmony_ci 1197db96d56Sopenharmony_ci curses.nocbreak() 1207db96d56Sopenharmony_ci stdscr.keypad(False) 1217db96d56Sopenharmony_ci curses.echo() 1227db96d56Sopenharmony_ci 1237db96d56Sopenharmony_cito reverse the curses-friendly terminal settings. Then call the 1247db96d56Sopenharmony_ci:func:`~curses.endwin` function to restore the terminal to its original 1257db96d56Sopenharmony_cioperating mode. :: 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ci curses.endwin() 1287db96d56Sopenharmony_ci 1297db96d56Sopenharmony_ciA common problem when debugging a curses application is to get your terminal 1307db96d56Sopenharmony_cimessed up when the application dies without restoring the terminal to its 1317db96d56Sopenharmony_ciprevious state. In Python this commonly happens when your code is buggy and 1327db96d56Sopenharmony_ciraises an uncaught exception. Keys are no longer echoed to the screen when 1337db96d56Sopenharmony_ciyou type them, for example, which makes using the shell difficult. 1347db96d56Sopenharmony_ci 1357db96d56Sopenharmony_ciIn Python you can avoid these complications and make debugging much easier by 1367db96d56Sopenharmony_ciimporting the :func:`curses.wrapper` function and using it like this:: 1377db96d56Sopenharmony_ci 1387db96d56Sopenharmony_ci from curses import wrapper 1397db96d56Sopenharmony_ci 1407db96d56Sopenharmony_ci def main(stdscr): 1417db96d56Sopenharmony_ci # Clear screen 1427db96d56Sopenharmony_ci stdscr.clear() 1437db96d56Sopenharmony_ci 1447db96d56Sopenharmony_ci # This raises ZeroDivisionError when i == 10. 1457db96d56Sopenharmony_ci for i in range(0, 11): 1467db96d56Sopenharmony_ci v = i-10 1477db96d56Sopenharmony_ci stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v)) 1487db96d56Sopenharmony_ci 1497db96d56Sopenharmony_ci stdscr.refresh() 1507db96d56Sopenharmony_ci stdscr.getkey() 1517db96d56Sopenharmony_ci 1527db96d56Sopenharmony_ci wrapper(main) 1537db96d56Sopenharmony_ci 1547db96d56Sopenharmony_ciThe :func:`~curses.wrapper` function takes a callable object and does the 1557db96d56Sopenharmony_ciinitializations described above, also initializing colors if color 1567db96d56Sopenharmony_cisupport is present. :func:`!wrapper` then runs your provided callable. 1577db96d56Sopenharmony_ciOnce the callable returns, :func:`!wrapper` will restore the original 1587db96d56Sopenharmony_cistate of the terminal. The callable is called inside a 1597db96d56Sopenharmony_ci:keyword:`try`...\ :keyword:`except` that catches exceptions, restores 1607db96d56Sopenharmony_cithe state of the terminal, and then re-raises the exception. Therefore 1617db96d56Sopenharmony_ciyour terminal won't be left in a funny state on exception and you'll be 1627db96d56Sopenharmony_ciable to read the exception's message and traceback. 1637db96d56Sopenharmony_ci 1647db96d56Sopenharmony_ci 1657db96d56Sopenharmony_ciWindows and Pads 1667db96d56Sopenharmony_ci================ 1677db96d56Sopenharmony_ci 1687db96d56Sopenharmony_ciWindows are the basic abstraction in curses. A window object represents a 1697db96d56Sopenharmony_cirectangular area of the screen, and supports methods to display text, 1707db96d56Sopenharmony_cierase it, allow the user to input strings, and so forth. 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ciThe ``stdscr`` object returned by the :func:`~curses.initscr` function is a 1737db96d56Sopenharmony_ciwindow object that covers the entire screen. Many programs may need 1747db96d56Sopenharmony_cionly this single window, but you might wish to divide the screen into 1757db96d56Sopenharmony_cismaller windows, in order to redraw or clear them separately. The 1767db96d56Sopenharmony_ci:func:`~curses.newwin` function creates a new window of a given size, 1777db96d56Sopenharmony_cireturning the new window object. :: 1787db96d56Sopenharmony_ci 1797db96d56Sopenharmony_ci begin_x = 20; begin_y = 7 1807db96d56Sopenharmony_ci height = 5; width = 40 1817db96d56Sopenharmony_ci win = curses.newwin(height, width, begin_y, begin_x) 1827db96d56Sopenharmony_ci 1837db96d56Sopenharmony_ciNote that the coordinate system used in curses is unusual. 1847db96d56Sopenharmony_ciCoordinates are always passed in the order *y,x*, and the top-left 1857db96d56Sopenharmony_cicorner of a window is coordinate (0,0). This breaks the normal 1867db96d56Sopenharmony_ciconvention for handling coordinates where the *x* coordinate comes 1877db96d56Sopenharmony_cifirst. This is an unfortunate difference from most other computer 1887db96d56Sopenharmony_ciapplications, but it's been part of curses since it was first written, 1897db96d56Sopenharmony_ciand it's too late to change things now. 1907db96d56Sopenharmony_ci 1917db96d56Sopenharmony_ciYour application can determine the size of the screen by using the 1927db96d56Sopenharmony_ci:data:`curses.LINES` and :data:`curses.COLS` variables to obtain the *y* and 1937db96d56Sopenharmony_ci*x* sizes. Legal coordinates will then extend from ``(0,0)`` to 1947db96d56Sopenharmony_ci``(curses.LINES - 1, curses.COLS - 1)``. 1957db96d56Sopenharmony_ci 1967db96d56Sopenharmony_ciWhen you call a method to display or erase text, the effect doesn't 1977db96d56Sopenharmony_ciimmediately show up on the display. Instead you must call the 1987db96d56Sopenharmony_ci:meth:`~curses.window.refresh` method of window objects to update the 1997db96d56Sopenharmony_ciscreen. 2007db96d56Sopenharmony_ci 2017db96d56Sopenharmony_ciThis is because curses was originally written with slow 300-baud 2027db96d56Sopenharmony_citerminal connections in mind; with these terminals, minimizing the 2037db96d56Sopenharmony_citime required to redraw the screen was very important. Instead curses 2047db96d56Sopenharmony_ciaccumulates changes to the screen and displays them in the most 2057db96d56Sopenharmony_ciefficient manner when you call :meth:`!refresh`. For example, if your 2067db96d56Sopenharmony_ciprogram displays some text in a window and then clears the window, 2077db96d56Sopenharmony_cithere's no need to send the original text because they're never 2087db96d56Sopenharmony_civisible. 2097db96d56Sopenharmony_ci 2107db96d56Sopenharmony_ciIn practice, explicitly telling curses to redraw a window doesn't 2117db96d56Sopenharmony_cireally complicate programming with curses much. Most programs go into a flurry 2127db96d56Sopenharmony_ciof activity, and then pause waiting for a keypress or some other action on the 2137db96d56Sopenharmony_cipart of the user. All you have to do is to be sure that the screen has been 2147db96d56Sopenharmony_ciredrawn before pausing to wait for user input, by first calling 2157db96d56Sopenharmony_ci:meth:`!stdscr.refresh` or the :meth:`!refresh` method of some other relevant 2167db96d56Sopenharmony_ciwindow. 2177db96d56Sopenharmony_ci 2187db96d56Sopenharmony_ciA pad is a special case of a window; it can be larger than the actual display 2197db96d56Sopenharmony_ciscreen, and only a portion of the pad displayed at a time. Creating a pad 2207db96d56Sopenharmony_cirequires the pad's height and width, while refreshing a pad requires giving the 2217db96d56Sopenharmony_cicoordinates of the on-screen area where a subsection of the pad will be 2227db96d56Sopenharmony_cidisplayed. :: 2237db96d56Sopenharmony_ci 2247db96d56Sopenharmony_ci pad = curses.newpad(100, 100) 2257db96d56Sopenharmony_ci # These loops fill the pad with letters; addch() is 2267db96d56Sopenharmony_ci # explained in the next section 2277db96d56Sopenharmony_ci for y in range(0, 99): 2287db96d56Sopenharmony_ci for x in range(0, 99): 2297db96d56Sopenharmony_ci pad.addch(y,x, ord('a') + (x*x+y*y) % 26) 2307db96d56Sopenharmony_ci 2317db96d56Sopenharmony_ci # Displays a section of the pad in the middle of the screen. 2327db96d56Sopenharmony_ci # (0,0) : coordinate of upper-left corner of pad area to display. 2337db96d56Sopenharmony_ci # (5,5) : coordinate of upper-left corner of window area to be filled 2347db96d56Sopenharmony_ci # with pad content. 2357db96d56Sopenharmony_ci # (20, 75) : coordinate of lower-right corner of window area to be 2367db96d56Sopenharmony_ci # : filled with pad content. 2377db96d56Sopenharmony_ci pad.refresh( 0,0, 5,5, 20,75) 2387db96d56Sopenharmony_ci 2397db96d56Sopenharmony_ciThe :meth:`!refresh` call displays a section of the pad in the rectangle 2407db96d56Sopenharmony_ciextending from coordinate (5,5) to coordinate (20,75) on the screen; the upper 2417db96d56Sopenharmony_cileft corner of the displayed section is coordinate (0,0) on the pad. Beyond 2427db96d56Sopenharmony_cithat difference, pads are exactly like ordinary windows and support the same 2437db96d56Sopenharmony_cimethods. 2447db96d56Sopenharmony_ci 2457db96d56Sopenharmony_ciIf you have multiple windows and pads on screen there is a more 2467db96d56Sopenharmony_ciefficient way to update the screen and prevent annoying screen flicker 2477db96d56Sopenharmony_cias each part of the screen gets updated. :meth:`!refresh` actually 2487db96d56Sopenharmony_cidoes two things: 2497db96d56Sopenharmony_ci 2507db96d56Sopenharmony_ci1) Calls the :meth:`~curses.window.noutrefresh` method of each window 2517db96d56Sopenharmony_ci to update an underlying data structure representing the desired 2527db96d56Sopenharmony_ci state of the screen. 2537db96d56Sopenharmony_ci2) Calls the function :func:`~curses.doupdate` function to change the 2547db96d56Sopenharmony_ci physical screen to match the desired state recorded in the data structure. 2557db96d56Sopenharmony_ci 2567db96d56Sopenharmony_ciInstead you can call :meth:`!noutrefresh` on a number of windows to 2577db96d56Sopenharmony_ciupdate the data structure, and then call :func:`!doupdate` to update 2587db96d56Sopenharmony_cithe screen. 2597db96d56Sopenharmony_ci 2607db96d56Sopenharmony_ci 2617db96d56Sopenharmony_ciDisplaying Text 2627db96d56Sopenharmony_ci=============== 2637db96d56Sopenharmony_ci 2647db96d56Sopenharmony_ciFrom a C programmer's point of view, curses may sometimes look like a 2657db96d56Sopenharmony_citwisty maze of functions, all subtly different. For example, 2667db96d56Sopenharmony_ci:c:func:`!addstr` displays a string at the current cursor location in 2677db96d56Sopenharmony_cithe ``stdscr`` window, while :c:func:`!mvaddstr` moves to a given y,x 2687db96d56Sopenharmony_cicoordinate first before displaying the string. :c:func:`!waddstr` is just 2697db96d56Sopenharmony_cilike :c:func:`!addstr`, but allows specifying a window to use instead of 2707db96d56Sopenharmony_ciusing ``stdscr`` by default. :c:func:`!mvwaddstr` allows specifying both 2717db96d56Sopenharmony_cia window and a coordinate. 2727db96d56Sopenharmony_ci 2737db96d56Sopenharmony_ciFortunately the Python interface hides all these details. ``stdscr`` 2747db96d56Sopenharmony_ciis a window object like any other, and methods such as 2757db96d56Sopenharmony_ci:meth:`~curses.window.addstr` accept multiple argument forms. Usually there 2767db96d56Sopenharmony_ciare four different forms. 2777db96d56Sopenharmony_ci 2787db96d56Sopenharmony_ci+---------------------------------+-----------------------------------------------+ 2797db96d56Sopenharmony_ci| Form | Description | 2807db96d56Sopenharmony_ci+=================================+===============================================+ 2817db96d56Sopenharmony_ci| *str* or *ch* | Display the string *str* or character *ch* at | 2827db96d56Sopenharmony_ci| | the current position | 2837db96d56Sopenharmony_ci+---------------------------------+-----------------------------------------------+ 2847db96d56Sopenharmony_ci| *str* or *ch*, *attr* | Display the string *str* or character *ch*, | 2857db96d56Sopenharmony_ci| | using attribute *attr* at the current | 2867db96d56Sopenharmony_ci| | position | 2877db96d56Sopenharmony_ci+---------------------------------+-----------------------------------------------+ 2887db96d56Sopenharmony_ci| *y*, *x*, *str* or *ch* | Move to position *y,x* within the window, and | 2897db96d56Sopenharmony_ci| | display *str* or *ch* | 2907db96d56Sopenharmony_ci+---------------------------------+-----------------------------------------------+ 2917db96d56Sopenharmony_ci| *y*, *x*, *str* or *ch*, *attr* | Move to position *y,x* within the window, and | 2927db96d56Sopenharmony_ci| | display *str* or *ch*, using attribute *attr* | 2937db96d56Sopenharmony_ci+---------------------------------+-----------------------------------------------+ 2947db96d56Sopenharmony_ci 2957db96d56Sopenharmony_ciAttributes allow displaying text in highlighted forms such as boldface, 2967db96d56Sopenharmony_ciunderline, reverse code, or in color. They'll be explained in more detail in 2977db96d56Sopenharmony_cithe next subsection. 2987db96d56Sopenharmony_ci 2997db96d56Sopenharmony_ci 3007db96d56Sopenharmony_ciThe :meth:`~curses.window.addstr` method takes a Python string or 3017db96d56Sopenharmony_cibytestring as the value to be displayed. The contents of bytestrings 3027db96d56Sopenharmony_ciare sent to the terminal as-is. Strings are encoded to bytes using 3037db96d56Sopenharmony_cithe value of the window's :attr:`~window.encoding` attribute; this defaults to 3047db96d56Sopenharmony_cithe default system encoding as returned by :func:`locale.getencoding`. 3057db96d56Sopenharmony_ci 3067db96d56Sopenharmony_ciThe :meth:`~curses.window.addch` methods take a character, which can be 3077db96d56Sopenharmony_cieither a string of length 1, a bytestring of length 1, or an integer. 3087db96d56Sopenharmony_ci 3097db96d56Sopenharmony_ciConstants are provided for extension characters; these constants are 3107db96d56Sopenharmony_ciintegers greater than 255. For example, :const:`ACS_PLMINUS` is a +/- 3117db96d56Sopenharmony_cisymbol, and :const:`ACS_ULCORNER` is the upper left corner of a box 3127db96d56Sopenharmony_ci(handy for drawing borders). You can also use the appropriate Unicode 3137db96d56Sopenharmony_cicharacter. 3147db96d56Sopenharmony_ci 3157db96d56Sopenharmony_ciWindows remember where the cursor was left after the last operation, so if you 3167db96d56Sopenharmony_cileave out the *y,x* coordinates, the string or character will be displayed 3177db96d56Sopenharmony_ciwherever the last operation left off. You can also move the cursor with the 3187db96d56Sopenharmony_ci``move(y,x)`` method. Because some terminals always display a flashing cursor, 3197db96d56Sopenharmony_ciyou may want to ensure that the cursor is positioned in some location where it 3207db96d56Sopenharmony_ciwon't be distracting; it can be confusing to have the cursor blinking at some 3217db96d56Sopenharmony_ciapparently random location. 3227db96d56Sopenharmony_ci 3237db96d56Sopenharmony_ciIf your application doesn't need a blinking cursor at all, you can 3247db96d56Sopenharmony_cicall ``curs_set(False)`` to make it invisible. For compatibility 3257db96d56Sopenharmony_ciwith older curses versions, there's a ``leaveok(bool)`` function 3267db96d56Sopenharmony_cithat's a synonym for :func:`~curses.curs_set`. When *bool* is true, the 3277db96d56Sopenharmony_cicurses library will attempt to suppress the flashing cursor, and you 3287db96d56Sopenharmony_ciwon't need to worry about leaving it in odd locations. 3297db96d56Sopenharmony_ci 3307db96d56Sopenharmony_ci 3317db96d56Sopenharmony_ciAttributes and Color 3327db96d56Sopenharmony_ci-------------------- 3337db96d56Sopenharmony_ci 3347db96d56Sopenharmony_ciCharacters can be displayed in different ways. Status lines in a text-based 3357db96d56Sopenharmony_ciapplication are commonly shown in reverse video, or a text viewer may need to 3367db96d56Sopenharmony_cihighlight certain words. curses supports this by allowing you to specify an 3377db96d56Sopenharmony_ciattribute for each cell on the screen. 3387db96d56Sopenharmony_ci 3397db96d56Sopenharmony_ciAn attribute is an integer, each bit representing a different 3407db96d56Sopenharmony_ciattribute. You can try to display text with multiple attribute bits 3417db96d56Sopenharmony_ciset, but curses doesn't guarantee that all the possible combinations 3427db96d56Sopenharmony_ciare available, or that they're all visually distinct. That depends on 3437db96d56Sopenharmony_cithe ability of the terminal being used, so it's safest to stick to the 3447db96d56Sopenharmony_cimost commonly available attributes, listed here. 3457db96d56Sopenharmony_ci 3467db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3477db96d56Sopenharmony_ci| Attribute | Description | 3487db96d56Sopenharmony_ci+======================+======================================+ 3497db96d56Sopenharmony_ci| :const:`A_BLINK` | Blinking text | 3507db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3517db96d56Sopenharmony_ci| :const:`A_BOLD` | Extra bright or bold text | 3527db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3537db96d56Sopenharmony_ci| :const:`A_DIM` | Half bright text | 3547db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3557db96d56Sopenharmony_ci| :const:`A_REVERSE` | Reverse-video text | 3567db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3577db96d56Sopenharmony_ci| :const:`A_STANDOUT` | The best highlighting mode available | 3587db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3597db96d56Sopenharmony_ci| :const:`A_UNDERLINE` | Underlined text | 3607db96d56Sopenharmony_ci+----------------------+--------------------------------------+ 3617db96d56Sopenharmony_ci 3627db96d56Sopenharmony_ciSo, to display a reverse-video status line on the top line of the screen, you 3637db96d56Sopenharmony_cicould code:: 3647db96d56Sopenharmony_ci 3657db96d56Sopenharmony_ci stdscr.addstr(0, 0, "Current mode: Typing mode", 3667db96d56Sopenharmony_ci curses.A_REVERSE) 3677db96d56Sopenharmony_ci stdscr.refresh() 3687db96d56Sopenharmony_ci 3697db96d56Sopenharmony_ciThe curses library also supports color on those terminals that provide it. The 3707db96d56Sopenharmony_cimost common such terminal is probably the Linux console, followed by color 3717db96d56Sopenharmony_cixterms. 3727db96d56Sopenharmony_ci 3737db96d56Sopenharmony_ciTo use color, you must call the :func:`~curses.start_color` function soon 3747db96d56Sopenharmony_ciafter calling :func:`~curses.initscr`, to initialize the default color set 3757db96d56Sopenharmony_ci(the :func:`curses.wrapper` function does this automatically). Once that's 3767db96d56Sopenharmony_cidone, the :func:`~curses.has_colors` function returns TRUE if the terminal 3777db96d56Sopenharmony_ciin use can 3787db96d56Sopenharmony_ciactually display color. (Note: curses uses the American spelling 'color', 3797db96d56Sopenharmony_ciinstead of the Canadian/British spelling 'colour'. If you're used to the 3807db96d56Sopenharmony_ciBritish spelling, you'll have to resign yourself to misspelling it for the sake 3817db96d56Sopenharmony_ciof these functions.) 3827db96d56Sopenharmony_ci 3837db96d56Sopenharmony_ciThe curses library maintains a finite number of color pairs, containing a 3847db96d56Sopenharmony_ciforeground (or text) color and a background color. You can get the attribute 3857db96d56Sopenharmony_civalue corresponding to a color pair with the :func:`~curses.color_pair` 3867db96d56Sopenharmony_cifunction; this can be bitwise-OR'ed with other attributes such as 3877db96d56Sopenharmony_ci:const:`A_REVERSE`, but again, such combinations are not guaranteed to work 3887db96d56Sopenharmony_cion all terminals. 3897db96d56Sopenharmony_ci 3907db96d56Sopenharmony_ciAn example, which displays a line of text using color pair 1:: 3917db96d56Sopenharmony_ci 3927db96d56Sopenharmony_ci stdscr.addstr("Pretty text", curses.color_pair(1)) 3937db96d56Sopenharmony_ci stdscr.refresh() 3947db96d56Sopenharmony_ci 3957db96d56Sopenharmony_ciAs I said before, a color pair consists of a foreground and background color. 3967db96d56Sopenharmony_ciThe ``init_pair(n, f, b)`` function changes the definition of color pair *n*, to 3977db96d56Sopenharmony_ciforeground color f and background color b. Color pair 0 is hard-wired to white 3987db96d56Sopenharmony_cion black, and cannot be changed. 3997db96d56Sopenharmony_ci 4007db96d56Sopenharmony_ciColors are numbered, and :func:`start_color` initializes 8 basic 4017db96d56Sopenharmony_cicolors when it activates color mode. They are: 0:black, 1:red, 4027db96d56Sopenharmony_ci2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The :mod:`curses` 4037db96d56Sopenharmony_cimodule defines named constants for each of these colors: 4047db96d56Sopenharmony_ci:const:`curses.COLOR_BLACK`, :const:`curses.COLOR_RED`, and so forth. 4057db96d56Sopenharmony_ci 4067db96d56Sopenharmony_ciLet's put all this together. To change color 1 to red text on a white 4077db96d56Sopenharmony_cibackground, you would call:: 4087db96d56Sopenharmony_ci 4097db96d56Sopenharmony_ci curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) 4107db96d56Sopenharmony_ci 4117db96d56Sopenharmony_ciWhen you change a color pair, any text already displayed using that color pair 4127db96d56Sopenharmony_ciwill change to the new colors. You can also display new text in this color 4137db96d56Sopenharmony_ciwith:: 4147db96d56Sopenharmony_ci 4157db96d56Sopenharmony_ci stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1)) 4167db96d56Sopenharmony_ci 4177db96d56Sopenharmony_ciVery fancy terminals can change the definitions of the actual colors to a given 4187db96d56Sopenharmony_ciRGB value. This lets you change color 1, which is usually red, to purple or 4197db96d56Sopenharmony_ciblue or any other color you like. Unfortunately, the Linux console doesn't 4207db96d56Sopenharmony_cisupport this, so I'm unable to try it out, and can't provide any examples. You 4217db96d56Sopenharmony_cican check if your terminal can do this by calling 4227db96d56Sopenharmony_ci:func:`~curses.can_change_color`, which returns ``True`` if the capability is 4237db96d56Sopenharmony_cithere. If you're lucky enough to have such a talented terminal, consult your 4247db96d56Sopenharmony_cisystem's man pages for more information. 4257db96d56Sopenharmony_ci 4267db96d56Sopenharmony_ci 4277db96d56Sopenharmony_ciUser Input 4287db96d56Sopenharmony_ci========== 4297db96d56Sopenharmony_ci 4307db96d56Sopenharmony_ciThe C curses library offers only very simple input mechanisms. Python's 4317db96d56Sopenharmony_ci:mod:`curses` module adds a basic text-input widget. (Other libraries 4327db96d56Sopenharmony_cisuch as `Urwid <https://pypi.org/project/urwid/>`_ have more extensive 4337db96d56Sopenharmony_cicollections of widgets.) 4347db96d56Sopenharmony_ci 4357db96d56Sopenharmony_ciThere are two methods for getting input from a window: 4367db96d56Sopenharmony_ci 4377db96d56Sopenharmony_ci* :meth:`~curses.window.getch` refreshes the screen and then waits for 4387db96d56Sopenharmony_ci the user to hit a key, displaying the key if :func:`~curses.echo` has been 4397db96d56Sopenharmony_ci called earlier. You can optionally specify a coordinate to which 4407db96d56Sopenharmony_ci the cursor should be moved before pausing. 4417db96d56Sopenharmony_ci 4427db96d56Sopenharmony_ci* :meth:`~curses.window.getkey` does the same thing but converts the 4437db96d56Sopenharmony_ci integer to a string. Individual characters are returned as 4447db96d56Sopenharmony_ci 1-character strings, and special keys such as function keys return 4457db96d56Sopenharmony_ci longer strings containing a key name such as ``KEY_UP`` or ``^G``. 4467db96d56Sopenharmony_ci 4477db96d56Sopenharmony_ciIt's possible to not wait for the user using the 4487db96d56Sopenharmony_ci:meth:`~curses.window.nodelay` window method. After ``nodelay(True)``, 4497db96d56Sopenharmony_ci:meth:`!getch` and :meth:`!getkey` for the window become 4507db96d56Sopenharmony_cinon-blocking. To signal that no input is ready, :meth:`!getch` returns 4517db96d56Sopenharmony_ci``curses.ERR`` (a value of -1) and :meth:`!getkey` raises an exception. 4527db96d56Sopenharmony_ciThere's also a :func:`~curses.halfdelay` function, which can be used to (in 4537db96d56Sopenharmony_cieffect) set a timer on each :meth:`!getch`; if no input becomes 4547db96d56Sopenharmony_ciavailable within a specified delay (measured in tenths of a second), 4557db96d56Sopenharmony_cicurses raises an exception. 4567db96d56Sopenharmony_ci 4577db96d56Sopenharmony_ciThe :meth:`!getch` method returns an integer; if it's between 0 and 255, it 4587db96d56Sopenharmony_cirepresents the ASCII code of the key pressed. Values greater than 255 are 4597db96d56Sopenharmony_cispecial keys such as Page Up, Home, or the cursor keys. You can compare the 4607db96d56Sopenharmony_civalue returned to constants such as :const:`curses.KEY_PPAGE`, 4617db96d56Sopenharmony_ci:const:`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. The main loop of 4627db96d56Sopenharmony_ciyour program may look something like this:: 4637db96d56Sopenharmony_ci 4647db96d56Sopenharmony_ci while True: 4657db96d56Sopenharmony_ci c = stdscr.getch() 4667db96d56Sopenharmony_ci if c == ord('p'): 4677db96d56Sopenharmony_ci PrintDocument() 4687db96d56Sopenharmony_ci elif c == ord('q'): 4697db96d56Sopenharmony_ci break # Exit the while loop 4707db96d56Sopenharmony_ci elif c == curses.KEY_HOME: 4717db96d56Sopenharmony_ci x = y = 0 4727db96d56Sopenharmony_ci 4737db96d56Sopenharmony_ciThe :mod:`curses.ascii` module supplies ASCII class membership functions that 4747db96d56Sopenharmony_citake either integer or 1-character string arguments; these may be useful in 4757db96d56Sopenharmony_ciwriting more readable tests for such loops. It also supplies 4767db96d56Sopenharmony_ciconversion functions that take either integer or 1-character-string arguments 4777db96d56Sopenharmony_ciand return the same type. For example, :func:`curses.ascii.ctrl` returns the 4787db96d56Sopenharmony_cicontrol character corresponding to its argument. 4797db96d56Sopenharmony_ci 4807db96d56Sopenharmony_ciThere's also a method to retrieve an entire string, 4817db96d56Sopenharmony_ci:meth:`~curses.window.getstr`. It isn't used very often, because its 4827db96d56Sopenharmony_cifunctionality is quite limited; the only editing keys available are 4837db96d56Sopenharmony_cithe backspace key and the Enter key, which terminates the string. It 4847db96d56Sopenharmony_cican optionally be limited to a fixed number of characters. :: 4857db96d56Sopenharmony_ci 4867db96d56Sopenharmony_ci curses.echo() # Enable echoing of characters 4877db96d56Sopenharmony_ci 4887db96d56Sopenharmony_ci # Get a 15-character string, with the cursor on the top line 4897db96d56Sopenharmony_ci s = stdscr.getstr(0,0, 15) 4907db96d56Sopenharmony_ci 4917db96d56Sopenharmony_ciThe :mod:`curses.textpad` module supplies a text box that supports an 4927db96d56Sopenharmony_ciEmacs-like set of keybindings. Various methods of the 4937db96d56Sopenharmony_ci:class:`~curses.textpad.Textbox` class support editing with input 4947db96d56Sopenharmony_civalidation and gathering the edit results either with or without 4957db96d56Sopenharmony_citrailing spaces. Here's an example:: 4967db96d56Sopenharmony_ci 4977db96d56Sopenharmony_ci import curses 4987db96d56Sopenharmony_ci from curses.textpad import Textbox, rectangle 4997db96d56Sopenharmony_ci 5007db96d56Sopenharmony_ci def main(stdscr): 5017db96d56Sopenharmony_ci stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)") 5027db96d56Sopenharmony_ci 5037db96d56Sopenharmony_ci editwin = curses.newwin(5,30, 2,1) 5047db96d56Sopenharmony_ci rectangle(stdscr, 1,0, 1+5+1, 1+30+1) 5057db96d56Sopenharmony_ci stdscr.refresh() 5067db96d56Sopenharmony_ci 5077db96d56Sopenharmony_ci box = Textbox(editwin) 5087db96d56Sopenharmony_ci 5097db96d56Sopenharmony_ci # Let the user edit until Ctrl-G is struck. 5107db96d56Sopenharmony_ci box.edit() 5117db96d56Sopenharmony_ci 5127db96d56Sopenharmony_ci # Get resulting contents 5137db96d56Sopenharmony_ci message = box.gather() 5147db96d56Sopenharmony_ci 5157db96d56Sopenharmony_ciSee the library documentation on :mod:`curses.textpad` for more details. 5167db96d56Sopenharmony_ci 5177db96d56Sopenharmony_ci 5187db96d56Sopenharmony_ciFor More Information 5197db96d56Sopenharmony_ci==================== 5207db96d56Sopenharmony_ci 5217db96d56Sopenharmony_ciThis HOWTO doesn't cover some advanced topics, such as reading the 5227db96d56Sopenharmony_cicontents of the screen or capturing mouse events from an xterm 5237db96d56Sopenharmony_ciinstance, but the Python library page for the :mod:`curses` module is now 5247db96d56Sopenharmony_cireasonably complete. You should browse it next. 5257db96d56Sopenharmony_ci 5267db96d56Sopenharmony_ciIf you're in doubt about the detailed behavior of the curses 5277db96d56Sopenharmony_cifunctions, consult the manual pages for your curses implementation, 5287db96d56Sopenharmony_ciwhether it's ncurses or a proprietary Unix vendor's. The manual pages 5297db96d56Sopenharmony_ciwill document any quirks, and provide complete lists of all the 5307db96d56Sopenharmony_cifunctions, attributes, and :const:`ACS_\*` characters available to 5317db96d56Sopenharmony_ciyou. 5327db96d56Sopenharmony_ci 5337db96d56Sopenharmony_ciBecause the curses API is so large, some functions aren't supported in 5347db96d56Sopenharmony_cithe Python interface. Often this isn't because they're difficult to 5357db96d56Sopenharmony_ciimplement, but because no one has needed them yet. Also, Python 5367db96d56Sopenharmony_cidoesn't yet support the menu library associated with ncurses. 5377db96d56Sopenharmony_ciPatches adding support for these would be welcome; see 5387db96d56Sopenharmony_ci`the Python Developer's Guide <https://devguide.python.org/>`_ to 5397db96d56Sopenharmony_cilearn more about submitting patches to Python. 5407db96d56Sopenharmony_ci 5417db96d56Sopenharmony_ci* `Writing Programs with NCURSES <https://invisible-island.net/ncurses/ncurses-intro.html>`_: 5427db96d56Sopenharmony_ci a lengthy tutorial for C programmers. 5437db96d56Sopenharmony_ci* `The ncurses man page <https://linux.die.net/man/3/ncurses>`_ 5447db96d56Sopenharmony_ci* `The ncurses FAQ <https://invisible-island.net/ncurses/ncurses.faq.html>`_ 5457db96d56Sopenharmony_ci* `"Use curses... don't swear" <https://www.youtube.com/watch?v=eN1eZtjLEnU>`_: 5467db96d56Sopenharmony_ci video of a PyCon 2013 talk on controlling terminals using curses or Urwid. 5477db96d56Sopenharmony_ci* `"Console Applications with Urwid" <https://pyvideo.org/video/1568/console-applications-with-urwid>`_: 5487db96d56Sopenharmony_ci video of a PyCon CA 2012 talk demonstrating some applications written using 5497db96d56Sopenharmony_ci Urwid. 550