Chapter 5 Exercise Set 5: Introducing Curses

Using Curses with Python

Python’s curses module provides “terminal handling for character-cell displays”.

Here is a “Hello Curses!” program in a file named hello_curses.py:

import curses
from curses import wrapper


def main(stdscr):
    stdscr.clear()
    stdscr.addstr(11, 32, "Hello CSC 221!")
    stdscr.refresh()
    stdscr.getch()


wrapper(main)

Notice that we are not using our usual print function here to display output, nor are we using input. Instead, we create a screen object, stdscr, and use its addstr method to print a string and its getch method to get a character.

In our next example, read_chars.py, we save the character returned by getchar an print out both its character and numeric representation:

import curses


def main(stdscr):
    curses.noecho()

    stdscr.addstr(9, 25, "Enter a character or '!' to quite: ")
    stdscr.refresh()
    ch = stdscr.getch()

    while ch != ord('!'):
        stdscr.clear()
        stdscr.addstr(9, 25, "Enter a character or '!' to quite: ")
        stdscr.addstr(
            12, 18,
            f"You entered '{chr(ch)}', which has a numeric value of {ch}."
        )
        stdscr.move(9, 60)
        stdscr.refresh()
        ch = stdscr.getch()


if __name__ == "__main__":
    curses.wrapper(main)

This method returns the numeric value of the key pressed, so we need to use Python’s char function convert into a printable character.