Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-updates > by-pkgid > e1011ddec34cda34f3a002b121247943 > files > 649

python-docs-2.7.17-1.1.mga7.noarch.rpm


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>Curses Programming with Python &#8212; Python 2.7.17 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.17 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Descriptor HowTo Guide" href="descriptor.html" />
    <link rel="prev" title="Porting Extension Modules to Python 3" href="cporting.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/curses.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.17 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="curses-programming-with-python">
<span id="curses-howto"></span><h1>Curses Programming with Python<a class="headerlink" href="#curses-programming-with-python" title="Permalink to this headline">¶</a></h1>
<dl class="field-list simple">
<dt class="field-odd">Author</dt>
<dd class="field-odd"><p>A.M. Kuchling, Eric S. Raymond</p>
</dd>
<dt class="field-even">Release</dt>
<dd class="field-even"><p>2.03</p>
</dd>
</dl>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document describes how to write text-mode programs with Python 2.x, using
the <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> extension module to control the display.</p>
</div>
<div class="section" id="what-is-curses">
<h2>What is curses?<a class="headerlink" href="#what-is-curses" title="Permalink to this headline">¶</a></h2>
<p>The curses library supplies a terminal-independent screen-painting and
keyboard-handling facility for text-based terminals; such terminals include
VT100s, the Linux console, and the simulated terminal provided by X11 programs
such as xterm and rxvt.  Display terminals support various control codes to
perform common operations such as moving the cursor, scrolling the screen, and
erasing areas.  Different terminals use widely differing codes, and often have
their own minor quirks.</p>
<p>In a world of X displays, one might ask “why bother”?  It’s true that
character-cell display terminals are an obsolete technology, but there are
niches in which being able to do fancy things with them are still valuable.  One
is on small-footprint or embedded Unixes that don’t carry an X server.  Another
is for tools like OS installers and kernel configurators that may have to run
before X is available.</p>
<p>The curses library hides all the details of different terminals, and provides
the programmer with an abstraction of a display, containing multiple
non-overlapping windows.  The contents of a window can be changed in various
ways—adding text, erasing it, changing its appearance—and the curses library
will automagically figure out what control codes need to be sent to the terminal
to produce the right output.</p>
<p>The curses library was originally written for BSD Unix; the later System V
versions of Unix from AT&amp;T added many enhancements and new functions. BSD curses
is no longer maintained, having been replaced by ncurses, which is an
open-source implementation of the AT&amp;T interface.  If you’re using an
open-source Unix such as Linux or FreeBSD, your system almost certainly uses
ncurses.  Since most current commercial Unix versions are based on System V
code, all the functions described here will probably be available.  The older
versions of curses carried by some proprietary Unixes may not support
everything, though.</p>
<p>No one has made a Windows port of the curses module.  On a Windows platform, try
the Console module written by Fredrik Lundh.  The Console module provides
cursor-addressable text output, plus full support for mouse and keyboard input,
and is available from <a class="reference external" href="http://effbot.org/zone/console-index.htm">http://effbot.org/zone/console-index.htm</a>.</p>
<div class="section" id="the-python-curses-module">
<h3>The Python curses module<a class="headerlink" href="#the-python-curses-module" title="Permalink to this headline">¶</a></h3>
<p>Thy Python module is a fairly simple wrapper over the C functions provided by
curses; if you’re already familiar with curses programming in C, it’s really
easy to transfer that knowledge to Python.  The biggest difference is that the
Python interface makes things simpler, by merging different C functions such as
<code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">mvaddstr()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">mvwaddstr()</span></code>, into a single
<code class="xref py py-meth docutils literal notranslate"><span class="pre">addstr()</span></code> method.  You’ll see this covered in more detail later.</p>
<p>This HOWTO is simply an introduction to writing text-mode programs with curses
and Python. It doesn’t attempt to be a complete guide to the curses API; for
that, see the Python library guide’s section on ncurses, and the C manual pages
for ncurses.  It will, however, give you the basic ideas.</p>
</div>
</div>
<div class="section" id="starting-and-ending-a-curses-application">
<h2>Starting and ending a curses application<a class="headerlink" href="#starting-and-ending-a-curses-application" title="Permalink to this headline">¶</a></h2>
<p>Before doing anything, curses must be initialized.  This is done by calling the
<code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> function, which will determine the terminal type, send any
required setup codes to the terminal, and create various internal data
structures.  If successful, <code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> returns a window object representing
the entire screen; this is usually called <code class="docutils literal notranslate"><span class="pre">stdscr</span></code>, after the name of the
corresponding C variable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">curses</span>
<span class="n">stdscr</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">initscr</span><span class="p">()</span>
</pre></div>
</div>
<p>Usually curses applications turn off automatic echoing of keys to the screen, in
order to be able to read keys and only display them under certain circumstances.
This requires calling the <code class="xref py py-func docutils literal notranslate"><span class="pre">noecho()</span></code> function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">noecho</span><span class="p">()</span>
</pre></div>
</div>
<p>Applications will also commonly need to react to keys instantly, without
requiring the Enter key to be pressed; this is called cbreak mode, as opposed to
the usual buffered input mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">cbreak</span><span class="p">()</span>
</pre></div>
</div>
<p>Terminals usually return special keys, such as the cursor keys or navigation
keys such as Page Up and Home, as a multibyte escape sequence.  While you could
write your application to expect such sequences and process them accordingly,
curses can do it for you, returning a special value such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_LEFT</span></code>.  To get curses to do the job, you’ll have to enable
keypad mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">keypad</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Terminating a curses application is much easier than starting one. You’ll need
to call</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">nocbreak</span><span class="p">();</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">keypad</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span> <span class="n">curses</span><span class="o">.</span><span class="n">echo</span><span class="p">()</span>
</pre></div>
</div>
<p>to reverse the curses-friendly terminal settings. Then call the <code class="xref py py-func docutils literal notranslate"><span class="pre">endwin()</span></code>
function to restore the terminal to its original operating mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">endwin</span><span class="p">()</span>
</pre></div>
</div>
<p>A common problem when debugging a curses application is to get your terminal
messed up when the application dies without restoring the terminal to its
previous state.  In Python this commonly happens when your code is buggy and
raises an uncaught exception.  Keys are no longer echoed to the screen when
you type them, for example, which makes using the shell difficult.</p>
<p>In Python you can avoid these complications and make debugging much easier by
importing the <a class="reference internal" href="../library/curses.html#curses.wrapper" title="curses.wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">curses.wrapper()</span></code></a> function.  It takes a callable and does
the initializations described above, also initializing colors if color support
is present.  It then runs your provided callable and finally deinitializes
appropriately.  The callable is called inside a try-catch clause which catches
exceptions, performs curses deinitialization, and then passes the exception
upwards.  Thus, your terminal won’t be left in a funny state on exception.</p>
</div>
<div class="section" id="windows-and-pads">
<h2>Windows and Pads<a class="headerlink" href="#windows-and-pads" title="Permalink to this headline">¶</a></h2>
<p>Windows are the basic abstraction in curses.  A window object represents a
rectangular area of the screen, and supports various methods to display text,
erase it, allow the user to input strings, and so forth.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> object returned by the <code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> function is a window
object that covers the entire screen.  Many programs may need only this single
window, but you might wish to divide the screen into smaller windows, in order
to redraw or clear them separately. The <code class="xref py py-func docutils literal notranslate"><span class="pre">newwin()</span></code> function creates a new
window of a given size, returning the new window object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">begin_x</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span> <span class="n">begin_y</span> <span class="o">=</span> <span class="mi">7</span>
<span class="n">height</span> <span class="o">=</span> <span class="mi">5</span><span class="p">;</span> <span class="n">width</span> <span class="o">=</span> <span class="mi">40</span>
<span class="n">win</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">newwin</span><span class="p">(</span><span class="n">height</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">begin_y</span><span class="p">,</span> <span class="n">begin_x</span><span class="p">)</span>
</pre></div>
</div>
<p>A word about the coordinate system used in curses: coordinates are always passed
in the order <em>y,x</em>, and the top-left corner of a window is coordinate (0,0).
This breaks a common convention for handling coordinates, where the <em>x</em>
coordinate usually comes first.  This is an unfortunate difference from most
other computer applications, but it’s been part of curses since it was first
written, and it’s too late to change things now.</p>
<p>When you call a method to display or erase text, the effect doesn’t immediately
show up on the display.  This is because curses was originally written with slow
300-baud terminal connections in mind; with these terminals, minimizing the time
required to redraw the screen is very important.  This lets curses accumulate
changes to the screen, and display them in the most efficient manner.  For
example, if your program displays some characters in a window, and then clears
the window, there’s no need to send the original characters because they’d never
be visible.</p>
<p>Accordingly, curses requires that you explicitly tell it to redraw windows,
using the <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> method of window objects.  In practice, this doesn’t
really complicate programming with curses much. Most programs go into a flurry
of activity, and then pause waiting for a keypress or some other action on the
part of the user.  All you have to do is to be sure that the screen has been
redrawn before pausing to wait for user input, by simply calling
<code class="docutils literal notranslate"><span class="pre">stdscr.refresh()</span></code> or the <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> method of some other relevant
window.</p>
<p>A pad is a special case of a window; it can be larger than the actual display
screen, and only a portion of it displayed at a time. Creating a pad simply
requires the pad’s height and width, while refreshing a pad requires giving the
coordinates of the on-screen area where a subsection of the pad will be
displayed.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pad</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">newpad</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="c1">#  These loops fill the pad with letters; this is</span>
<span class="c1"># explained in the next section</span>
<span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">pad</span><span class="o">.</span><span class="n">addch</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="n">x</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="p">)</span> <span class="o">%</span> <span class="mi">26</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">curses</span><span class="o">.</span><span class="n">error</span><span class="p">:</span>
            <span class="k">pass</span>

<span class="c1">#  Displays a section of the pad in the middle of the screen</span>
<span class="n">pad</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span><span class="mi">75</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> call displays a section of the pad in the rectangle
extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper
left corner of the displayed section is coordinate (0,0) on the pad.  Beyond
that difference, pads are exactly like ordinary windows and support the same
methods.</p>
<p>If you have multiple windows and pads on screen there is a more efficient way to
go, which will prevent annoying screen flicker at refresh time.  Use the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code> method of each window to update the data structure
representing the desired state of the screen; then change the physical screen to
match the desired state in one go with the function <code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code>.  The
normal <code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code> method calls <code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code> as its last act.</p>
</div>
<div class="section" id="displaying-text">
<h2>Displaying Text<a class="headerlink" href="#displaying-text" title="Permalink to this headline">¶</a></h2>
<p>From a C programmer’s point of view, curses may sometimes look like a twisty
maze of functions, all subtly different.  For example, <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> displays a
string at the current cursor location in the <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> window, while
<code class="xref py py-func docutils literal notranslate"><span class="pre">mvaddstr()</span></code> moves to a given y,x coordinate first before displaying the
string. <code class="xref py py-func docutils literal notranslate"><span class="pre">waddstr()</span></code> is just like <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code>, but allows specifying a
window to use, instead of using <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> by default. <code class="xref py py-func docutils literal notranslate"><span class="pre">mvwaddstr()</span></code> follows
similarly.</p>
<p>Fortunately the Python interface hides all these details; <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> is a window
object like any other, and methods like <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> accept multiple argument
forms.  Usually there are four different forms.</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 41%" />
<col style="width: 59%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>Form</p></th>
<th class="head"><p>Description</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><em>str</em> or <em>ch</em></p></td>
<td><p>Display the string <em>str</em> or character <em>ch</em> at
the current position</p></td>
</tr>
<tr class="row-odd"><td><p><em>str</em> or <em>ch</em>, <em>attr</em></p></td>
<td><p>Display the string <em>str</em> or character <em>ch</em>,
using attribute <em>attr</em> at the current
position</p></td>
</tr>
<tr class="row-even"><td><p><em>y</em>, <em>x</em>, <em>str</em> or <em>ch</em></p></td>
<td><p>Move to position <em>y,x</em> within the window, and
display <em>str</em> or <em>ch</em></p></td>
</tr>
<tr class="row-odd"><td><p><em>y</em>, <em>x</em>, <em>str</em> or <em>ch</em>, <em>attr</em></p></td>
<td><p>Move to position <em>y,x</em> within the window, and
display <em>str</em> or <em>ch</em>, using attribute <em>attr</em></p></td>
</tr>
</tbody>
</table>
<p>Attributes allow displaying text in highlighted forms, such as in boldface,
underline, reverse code, or in color.  They’ll be explained in more detail in
the next subsection.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> function takes a Python string as the value to be displayed,
while the <code class="xref py py-func docutils literal notranslate"><span class="pre">addch()</span></code> functions take a character, which can be either a Python
string of length 1 or an integer.  If it’s a string, you’re limited to
displaying characters between 0 and 255.  SVr4 curses provides constants for
extension characters; these constants are integers greater than 255.  For
example, <code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_PLMINUS</span></code> is a +/- symbol, and <code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_ULCORNER</span></code> is the
upper left corner of a box (handy for drawing borders).</p>
<p>Windows remember where the cursor was left after the last operation, so if you
leave out the <em>y,x</em> coordinates, the string or character will be displayed
wherever the last operation left off.  You can also move the cursor with the
<code class="docutils literal notranslate"><span class="pre">move(y,x)</span></code> method.  Because some terminals always display a flashing cursor,
you may want to ensure that the cursor is positioned in some location where it
won’t be distracting; it can be confusing to have the cursor blinking at some
apparently random location.</p>
<p>If your application doesn’t need a blinking cursor at all, you can call
<code class="docutils literal notranslate"><span class="pre">curs_set(0)</span></code> to make it invisible.  Equivalently, and for compatibility with
older curses versions, there’s a <code class="docutils literal notranslate"><span class="pre">leaveok(bool)</span></code> function.  When <em>bool</em> is
true, the curses library will attempt to suppress the flashing cursor, and you
won’t need to worry about leaving it in odd locations.</p>
<div class="section" id="attributes-and-color">
<h3>Attributes and Color<a class="headerlink" href="#attributes-and-color" title="Permalink to this headline">¶</a></h3>
<p>Characters can be displayed in different ways.  Status lines in a text-based
application are commonly shown in reverse video; a text viewer may need to
highlight certain words.  curses supports this by allowing you to specify an
attribute for each cell on the screen.</p>
<p>An attribute is an integer, each bit representing a different attribute.  You can
try to display text with multiple attribute bits set, but curses doesn’t
guarantee that all the possible combinations are available, or that they’re all
visually distinct.  That depends on the ability of the terminal being used, so
it’s safest to stick to the most commonly available attributes, listed here.</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 37%" />
<col style="width: 63%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>Attribute</p></th>
<th class="head"><p>Description</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_BLINK</span></code></p></td>
<td><p>Blinking text</p></td>
</tr>
<tr class="row-odd"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_BOLD</span></code></p></td>
<td><p>Extra bright or bold text</p></td>
</tr>
<tr class="row-even"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_DIM</span></code></p></td>
<td><p>Half bright text</p></td>
</tr>
<tr class="row-odd"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_REVERSE</span></code></p></td>
<td><p>Reverse-video text</p></td>
</tr>
<tr class="row-even"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_STANDOUT</span></code></p></td>
<td><p>The best highlighting mode available</p></td>
</tr>
<tr class="row-odd"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">A_UNDERLINE</span></code></p></td>
<td><p>Underlined text</p></td>
</tr>
</tbody>
</table>
<p>So, to display a reverse-video status line on the top line of the screen, you
could code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;Current mode: Typing mode&quot;</span><span class="p">,</span>
              <span class="n">curses</span><span class="o">.</span><span class="n">A_REVERSE</span><span class="p">)</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">refresh</span><span class="p">()</span>
</pre></div>
</div>
<p>The curses library also supports color on those terminals that provide it. The
most common such terminal is probably the Linux console, followed by color
xterms.</p>
<p>To use color, you must call the <code class="xref py py-func docutils literal notranslate"><span class="pre">start_color()</span></code> function soon after calling
<code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code>, to initialize the default color set (the
<code class="xref py py-func docutils literal notranslate"><span class="pre">curses.wrapper.wrapper()</span></code> function does this automatically).  Once that’s
done, the <code class="xref py py-func docutils literal notranslate"><span class="pre">has_colors()</span></code> function returns TRUE if the terminal in use can
actually display color.  (Note: curses uses the American spelling ‘color’,
instead of the Canadian/British spelling ‘colour’.  If you’re used to the
British spelling, you’ll have to resign yourself to misspelling it for the sake
of these functions.)</p>
<p>The curses library maintains a finite number of color pairs, containing a
foreground (or text) color and a background color.  You can get the attribute
value corresponding to a color pair with the <code class="xref py py-func docutils literal notranslate"><span class="pre">color_pair()</span></code> function; this
can be bitwise-OR’ed with other attributes such as <code class="xref py py-const docutils literal notranslate"><span class="pre">A_REVERSE</span></code>, but
again, such combinations are not guaranteed to work on all terminals.</p>
<p>An example, which displays a line of text using color pair 1:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="s2">&quot;Pretty text&quot;</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">color_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">refresh</span><span class="p">()</span>
</pre></div>
</div>
<p>As I said before, a color pair consists of a foreground and background color.
<code class="xref py py-func docutils literal notranslate"><span class="pre">start_color()</span></code> initializes 8 basic colors when it activates color mode.
They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
7:white.  The curses module defines named constants for each of these colors:
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.COLOR_BLACK</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.COLOR_RED</span></code>, and so forth.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">init_pair(n,</span> <span class="pre">f,</span> <span class="pre">b)</span></code> function changes the definition of color pair <em>n</em>, to
foreground color f and background color b.  Color pair 0 is hard-wired to white
on black, and cannot be changed.</p>
<p>Let’s put all this together. To change color 1 to red text on a white
background, you would call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">init_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">COLOR_RED</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">COLOR_WHITE</span><span class="p">)</span>
</pre></div>
</div>
<p>When you change a color pair, any text already displayed using that color pair
will change to the new colors.  You can also display new text in this color
with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;RED ALERT!&quot;</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">color_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
</pre></div>
</div>
<p>Very fancy terminals can change the definitions of the actual colors to a given
RGB value.  This lets you change color 1, which is usually red, to purple or
blue or any other color you like.  Unfortunately, the Linux console doesn’t
support this, so I’m unable to try it out, and can’t provide any examples.  You
can check if your terminal can do this by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">can_change_color()</span></code>,
which returns TRUE if the capability is there.  If you’re lucky enough to have
such a talented terminal, consult your system’s man pages for more information.</p>
</div>
</div>
<div class="section" id="user-input">
<h2>User Input<a class="headerlink" href="#user-input" title="Permalink to this headline">¶</a></h2>
<p>The curses library itself offers only very simple input mechanisms. Python’s
support adds a text-input widget that makes up some of the lack.</p>
<p>The most common way to get input to a window is to use its <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> method.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> pauses and waits for the user to hit a key, displaying it if
<code class="xref py py-func docutils literal notranslate"><span class="pre">echo()</span></code> has been called earlier.  You can optionally specify a coordinate
to which the cursor should be moved before pausing.</p>
<p>It’s possible to change this behavior with the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">nodelay()</span></code>. After
<code class="docutils literal notranslate"><span class="pre">nodelay(1)</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> for the window becomes non-blocking and returns
<code class="docutils literal notranslate"><span class="pre">curses.ERR</span></code> (a value of -1) when no input is ready.  There’s also a
<code class="xref py py-func docutils literal notranslate"><span class="pre">halfdelay()</span></code> function, which can be used to (in effect) set a timer on each
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code>; if no input becomes available within a specified
delay (measured in tenths of a second), curses raises an exception.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> method returns an integer; if it’s between 0 and 255, it
represents the ASCII code of the key pressed.  Values greater than 255 are
special keys such as Page Up, Home, or the cursor keys. You can compare the
value returned to constants such as <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_PPAGE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_HOME</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_LEFT</span></code>.  Usually the main loop of
your program will look something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">getch</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">c</span> <span class="o">==</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;p&#39;</span><span class="p">):</span>
        <span class="n">PrintDocument</span><span class="p">()</span>
    <span class="k">elif</span> <span class="n">c</span> <span class="o">==</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;q&#39;</span><span class="p">):</span>
        <span class="k">break</span>  <span class="c1"># Exit the while()</span>
    <span class="k">elif</span> <span class="n">c</span> <span class="o">==</span> <span class="n">curses</span><span class="o">.</span><span class="n">KEY_HOME</span><span class="p">:</span>
        <span class="n">x</span> <span class="o">=</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">0</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/curses.ascii.html#module-curses.ascii" title="curses.ascii: Constants and set-membership functions for ASCII characters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.ascii</span></code></a> module supplies ASCII class membership functions that
take either integer or 1-character-string arguments; these may be useful in
writing more readable tests for your command interpreters.  It also supplies
conversion functions  that take either integer or 1-character-string arguments
and return the same type.  For example, <a class="reference internal" href="../library/curses.ascii.html#curses.ascii.ctrl" title="curses.ascii.ctrl"><code class="xref py py-func docutils literal notranslate"><span class="pre">curses.ascii.ctrl()</span></code></a> returns the
control character corresponding to its argument.</p>
<p>There’s also a method to retrieve an entire string, <code class="xref py py-const docutils literal notranslate"><span class="pre">getstr()</span></code>.  It isn’t
used very often, because its functionality is quite limited; the only editing
keys available are the backspace key and the Enter key, which terminates the
string.  It can optionally be limited to a fixed number of characters.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">echo</span><span class="p">()</span>            <span class="c1"># Enable echoing of characters</span>

<span class="c1"># Get a 15-character string, with the cursor on the top line</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">getstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mi">15</span><span class="p">)</span>
</pre></div>
</div>
<p>The Python <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module supplies something better. With it, you
can turn a window into a text box that supports an Emacs-like set of
keybindings.  Various methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> class support editing with
input validation and gathering the edit results either with or without trailing
spaces.   See the library documentation on <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> for the
details.</p>
</div>
<div class="section" id="for-more-information">
<h2>For More Information<a class="headerlink" href="#for-more-information" title="Permalink to this headline">¶</a></h2>
<p>This HOWTO didn’t cover some advanced topics, such as screen-scraping or
capturing mouse events from an xterm instance.  But the Python library page for
the curses modules is now pretty complete.  You should browse it next.</p>
<p>If you’re in doubt about the detailed behavior of any of the ncurses entry
points, consult the manual pages for your curses implementation, whether it’s
ncurses or a proprietary Unix vendor’s.  The manual pages will document any
quirks, and provide complete lists of all the functions, attributes, and
<code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_*</span></code> characters available to you.</p>
<p>Because the curses API is so large, some functions aren’t supported in the
Python interface, not because they’re difficult to implement, but because no one
has needed them yet.  Feel free to add them and then submit a patch.  Also, we
don’t yet have support for the menu library associated with
ncurses; feel free to add that.</p>
<p>If you write an interesting little program, feel free to contribute it as
another demo.  We can always use more of them!</p>
<p>The ncurses FAQ: <a class="reference external" href="http://invisible-island.net/ncurses/ncurses.faq.html">http://invisible-island.net/ncurses/ncurses.faq.html</a></p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Curses Programming with Python</a><ul>
<li><a class="reference internal" href="#what-is-curses">What is curses?</a><ul>
<li><a class="reference internal" href="#the-python-curses-module">The Python curses module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#starting-and-ending-a-curses-application">Starting and ending a curses application</a></li>
<li><a class="reference internal" href="#windows-and-pads">Windows and Pads</a></li>
<li><a class="reference internal" href="#displaying-text">Displaying Text</a><ul>
<li><a class="reference internal" href="#attributes-and-color">Attributes and Color</a></li>
</ul>
</li>
<li><a class="reference internal" href="#user-input">User Input</a></li>
<li><a class="reference internal" href="#for-more-information">For More Information</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cporting.html"
                        title="previous chapter">Porting Extension Modules to Python 3</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="descriptor.html"
                        title="next chapter">Descriptor HowTo Guide</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/curses.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             >next</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.17 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 19, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
    </div>

  </body>
</html>