• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""curses.wrapper
2
3Contains one function, wrapper(), which runs another function which
4should be the rest of your curses-based application.  If the
5application raises an exception, wrapper() will restore the terminal
6to a sane state so you can read the resulting traceback.
7
8"""
9
10import curses
11
12def wrapper(func, *args, **kwds):
13    """Wrapper function that initializes curses and calls another function,
14    restoring normal keyboard/screen behavior on error.
15    The callable object 'func' is then passed the main window 'stdscr'
16    as its first argument, followed by any other arguments passed to
17    wrapper().
18    """
19
20    try:
21        # Initialize curses
22        stdscr = curses.initscr()
23
24        # Turn off echoing of keys, and enter cbreak mode,
25        # where no buffering is performed on keyboard input
26        curses.noecho()
27        curses.cbreak()
28
29        # In keypad mode, escape sequences for special keys
30        # (like the cursor keys) will be interpreted and
31        # a special value like curses.KEY_LEFT will be returned
32        stdscr.keypad(1)
33
34        # Start color, too.  Harmless if the terminal doesn't have
35        # color; user can test with has_color() later on.  The try/catch
36        # works around a minor bit of over-conscientiousness in the curses
37        # module -- the error return from C start_color() is ignorable.
38        try:
39            curses.start_color()
40        except:
41            pass
42
43        return func(stdscr, *args, **kwds)
44    finally:
45        # Set everything back to normal
46        if 'stdscr' in locals():
47            stdscr.keypad(0)
48            curses.echo()
49            curses.nocbreak()
50            curses.endwin()
51