Andrew M. Kuchling | d0939fa | 2000-06-10 23:06:53 +0000 | [diff] [blame] | 1 | """curses.wrapper |
| 2 | |
| 3 | Contains one function, wrapper(), which runs another function which |
| 4 | should be the rest of your curses-based application. If the |
| 5 | application raises an exception, wrapper() will restore the terminal |
| 6 | to a sane state so you can read the resulting traceback. |
| 7 | |
| 8 | """ |
| 9 | |
| 10 | import sys, curses |
| 11 | |
| 12 | def 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. Kuchling | 8f790fe | 2000-06-27 00:50:40 +0000 | [diff] [blame] | 20 | res = None |
Andrew M. Kuchling | d0939fa | 2000-06-10 23:06:53 +0000 | [diff] [blame] | 21 | try: |
| 22 | # Initialize curses |
Jeremy Hylton | 2ea17fa | 2000-07-07 21:02:22 +0000 | [diff] [blame] | 23 | stdscr=curses.initscr() |
Andrew M. Kuchling | 8f790fe | 2000-06-27 00:50:40 +0000 | [diff] [blame] | 24 | |
Andrew M. Kuchling | d0939fa | 2000-06-10 23:06:53 +0000 | [diff] [blame] | 25 | # Turn off echoing of keys, and enter cbreak mode, |
| 26 | # where no buffering is performed on keyboard input |
Jeremy Hylton | 2ea17fa | 2000-07-07 21:02:22 +0000 | [diff] [blame] | 27 | curses.noecho() |
| 28 | curses.cbreak() |
Andrew M. Kuchling | d0939fa | 2000-06-10 23:06:53 +0000 | [diff] [blame] | 29 | |
| 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 | |
Andrew M. Kuchling | 8f790fe | 2000-06-27 00:50:40 +0000 | [diff] [blame] | 35 | res = apply(func, (stdscr,) + rest) |
| 36 | except: |
| 37 | # In the event of an error, restore the terminal |
| 38 | # to a sane state. |
Jeremy Hylton | 2ea17fa | 2000-07-07 21:02:22 +0000 | [diff] [blame] | 39 | stdscr.keypad(0) |
| 40 | curses.echo() |
| 41 | curses.nocbreak() |
| 42 | curses.endwin() |
Andrew M. Kuchling | 8f790fe | 2000-06-27 00:50:40 +0000 | [diff] [blame] | 43 | |
| 44 | # Pass the exception upwards |
| 45 | (exc_type, exc_value, exc_traceback) = sys.exc_info() |
| 46 | raise exc_type, exc_value, exc_traceback |
| 47 | else: |
| 48 | # Set everything back to normal |
Jeremy Hylton | 2ea17fa | 2000-07-07 21:02:22 +0000 | [diff] [blame] | 49 | stdscr.keypad(0) |
| 50 | curses.echo() |
| 51 | curses.nocbreak() |
| 52 | curses.endwin() # Terminate curses |
Andrew M. Kuchling | d0939fa | 2000-06-10 23:06:53 +0000 | [diff] [blame] | 53 | |
Andrew M. Kuchling | 8f790fe | 2000-06-27 00:50:40 +0000 | [diff] [blame] | 54 | return res |