<?php include('HEADER.php'); ?>

<h1>Python &amp; Curses</h1>

<p>curses is a library for manipulating terminal displays. It was originally developed to support the game <code>rogue</code> on early BSD Unix, but is now widely used to provide an interface for a variety of tools (installers, system conguration, etc.) on Linux and many unix-like platforms. (The original curses has been supplanted by <code>ncurses</code>, which started as a free clone of curses but has become the de-facto extended standard.)</p>

<p>The basic curses unit is the <i>window</i>. Windows which are as large as the entire terminal display are called <i>screens</i>. By default, curses creates two windows/screens: <code>curscr</code> and <code>stdscr</code>. <code>curscr</code> contains the actual current contents of the terminal. <code>stdscr</code> is like an off-screen draw buffer that includes what will be flushed to <code>curscr</code> as soon as we call <code>refresh()</code>. We never really want to touch <code>curscr</code> directly.</p>

<p>Note: when using coordinates, curses orders them as y, x (i.e. high, wide) rather than the more typical x, y.</p>

<h2>Minimal Python Curses Example</h2>

<pre>#!/usr/bin/env python

import curses
import time

def centerStringInWindow(window, string):
    height, width = window.getmaxyx()
    yorigin = (height / 2) - 1
    xorigin = (width / 2) - (len(string) / 2)
    window.addstr(yorigin, xorigin, string)
    return

def main(stdscr):
    stdscr.clear()
    hello = 'Hello, world!'
    bye = 'Goodbye.'
    stdscr.addstr(hello)
    stdscr.refresh()
    while 1:
        c = stdscr.getch()
        if c == ord('q'):
            stdscr.clear()
            centerStringInWindow(stdscr, bye)
            stdscr.refresh()
            time.sleep(2)
            break
        elif c == ord('h'):
            helpMessage = 'Press "q" to quit.'
            centerStringInWindow(stdscr, helpMessage)
            stdscr.refresh()

if __name__ == '__main__':
    # curses.wrapper takes care of terminal initialization and cleanup for us:
    curses.wrapper(main)</pre>

<h2>References</h2>

<ul>
<li><a href="http://invisible-island.net/ncurses/ncurses-intro.html">Writing Programs with NCURSES</a></li>
<li><a href="https://docs.python.org/3/howto/curses.html">Curses Programming with Python</a></li>
</ul>

<?php include('../FOOTER.php'); ?>
