blob: cd3008616ff4edf66fa478b10af71bdedd6196fe [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
23 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
27 curses.noecho() ; 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
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000034 res = apply(func, (stdscr,) + rest)
35 except:
36 # In the event of an error, restore the terminal
37 # to a sane state.
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000038 stdscr.keypad(0)
39 curses.echo() ; curses.nocbreak()
40 curses.endwin()
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000041
42 # Pass the exception upwards
43 (exc_type, exc_value, exc_traceback) = sys.exc_info()
44 raise exc_type, exc_value, exc_traceback
45 else:
46 # Set everything back to normal
47 stdscr.keypad(0)
48 curses.echo() ; curses.nocbreak()
49 curses.endwin() # Terminate curses
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000050
Andrew M. Kuchling8f790fe2000-06-27 00:50:40 +000051 return res