blob: 51fb7240dc7f59d0e074ba01089e3300e9b1b81f [file] [log] [blame]
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +00001"""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 sys, curses
11
12def wrapper(func, *rest):
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
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000020 res = None
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000021 try:
22 # Initialize curses
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000023 stdscr=curses.initscr()
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000024
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000025 # Turn off echoing of keys, and enter cbreak mode,
26 # where no buffering is performed on keyboard input
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000027 curses.noecho()
28 curses.cbreak()
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000029
30 # In keypad mode, escape sequences for special keys
31 # (like the cursor keys) will be interpreted and
32 # a special value like curses.KEY_LEFT will be returned
33 stdscr.keypad(1)
34
Eric S. Raymond1ebd3f62000-08-09 21:11:07 +000035 # Start color, too. Harmless if the terminal doesn't have
36 # color; user can test with has_color() later on. The try/catch
37 # works around a minor bit of over-conscientiousness in the curses
38 # module -- the error return from C start_color() is ignorable.
39 try:
40 curses.start_color()
41 except:
42 pass
43
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000044 res = apply(func, (stdscr,) + rest)
45 except:
46 # In the event of an error, restore the terminal
47 # to a sane state.
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000048 stdscr.keypad(0)
49 curses.echo()
50 curses.nocbreak()
51 curses.endwin()
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000052
53 # Pass the exception upwards
54 (exc_type, exc_value, exc_traceback) = sys.exc_info()
55 raise exc_type, exc_value, exc_traceback
56 else:
57 # Set everything back to normal
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000058 stdscr.keypad(0)
59 curses.echo()
60 curses.nocbreak()
61 curses.endwin() # Terminate curses
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000062
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000063 return res