• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""curses
2
3The main package for curses support for Python.  Normally used by importing
4the package, and perhaps a particular module inside it.
5
6   import curses
7   from curses import textpad
8   curses.initscr()
9   ...
10
11"""
12
13from _curses import *
14import os as _os
15import sys as _sys
16
17# Some constants, most notably the ACS_* ones, are only added to the C
18# _curses module's dictionary after initscr() is called.  (Some
19# versions of SGI's curses don't define values for those constants
20# until initscr() has been called.)  This wrapper function calls the
21# underlying C initscr(), and then copies the constants from the
22# _curses module to the curses package's dictionary.  Don't do 'from
23# curses import *' if you'll be needing the ACS_* constants.
24
25def initscr():
26    import _curses, curses
27    # we call setupterm() here because it raises an error
28    # instead of calling exit() in error cases.
29    setupterm(term=_os.environ.get("TERM", "unknown"),
30              fd=_sys.__stdout__.fileno())
31    stdscr = _curses.initscr()
32    for key, value in _curses.__dict__.items():
33        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
34            setattr(curses, key, value)
35
36    return stdscr
37
38# This is a similar wrapper for start_color(), which adds the COLORS and
39# COLOR_PAIRS variables which are only available after start_color() is
40# called.
41
42def start_color():
43    import _curses, curses
44    retval = _curses.start_color()
45    if hasattr(_curses, 'COLORS'):
46        curses.COLORS = _curses.COLORS
47    if hasattr(_curses, 'COLOR_PAIRS'):
48        curses.COLOR_PAIRS = _curses.COLOR_PAIRS
49    return retval
50
51# Import Python has_key() implementation if _curses doesn't contain has_key()
52
53try:
54    has_key
55except NameError:
56    from .has_key import has_key
57
58# Wrapper for the entire curses-based application.  Runs a function which
59# should be the rest of your curses-based application.  If the application
60# raises an exception, wrapper() will restore the terminal to a sane state so
61# you can read the resulting traceback.
62
63def wrapper(*args, **kwds):
64    """Wrapper function that initializes curses and calls another function,
65    restoring normal keyboard/screen behavior on error.
66    The callable object 'func' is then passed the main window 'stdscr'
67    as its first argument, followed by any other arguments passed to
68    wrapper().
69    """
70
71    if args:
72        func, *args = args
73    elif 'func' in kwds:
74        func = kwds.pop('func')
75        import warnings
76        warnings.warn("Passing 'func' as keyword argument is deprecated",
77                      DeprecationWarning, stacklevel=2)
78    else:
79        raise TypeError('wrapper expected at least 1 positional argument, '
80                        'got %d' % len(args))
81
82    try:
83        # Initialize curses
84        stdscr = initscr()
85
86        # Turn off echoing of keys, and enter cbreak mode,
87        # where no buffering is performed on keyboard input
88        noecho()
89        cbreak()
90
91        # In keypad mode, escape sequences for special keys
92        # (like the cursor keys) will be interpreted and
93        # a special value like curses.KEY_LEFT will be returned
94        stdscr.keypad(1)
95
96        # Start color, too.  Harmless if the terminal doesn't have
97        # color; user can test with has_color() later on.  The try/catch
98        # works around a minor bit of over-conscientiousness in the curses
99        # module -- the error return from C start_color() is ignorable.
100        try:
101            start_color()
102        except:
103            pass
104
105        return func(stdscr, *args, **kwds)
106    finally:
107        # Set everything back to normal
108        if 'stdscr' in locals():
109            stdscr.keypad(0)
110            echo()
111            nocbreak()
112            endwin()
113wrapper.__text_signature__ = '(func, /, *args, **kwds)'
114