|
| 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 | + |
| 20 | + res = None |
| 21 | + try: |
| 22 | + # Initialize curses |
| 23 | + stdscr=curses.initscr() |
| 24 | + # Turn off echoing of keys, and enter cbreak mode, |
| 25 | + # where no buffering is performed on keyboard input |
| 26 | + curses.noecho() ; curses.cbreak() |
| 27 | + |
| 28 | + # In keypad mode, escape sequences for special keys |
| 29 | + # (like the cursor keys) will be interpreted and |
| 30 | + # a special value like curses.KEY_LEFT will be returned |
| 31 | + stdscr.keypad(1) |
| 32 | + |
| 33 | + res = apply(func, (stdscr,) + rest) |
| 34 | + except: |
| 35 | + # In the event of an error, restore the terminal |
| 36 | + # to a sane state. |
| 37 | + stdscr.keypad(0) |
| 38 | + curses.echo() ; curses.nocbreak() |
| 39 | + curses.endwin() |
| 40 | + # Pass the exception upwards |
| 41 | + (exc_type, exc_value, exc_traceback) = sys.exc_info() |
| 42 | + raise exc_type, exc_value, exc_traceback |
| 43 | + else: |
| 44 | + # Set everything back to normal |
| 45 | + stdscr.keypad(0) |
| 46 | + curses.echo() ; curses.nocbreak() |
| 47 | + curses.endwin() # Terminate curses |
| 48 | + |
| 49 | + return res |
| 50 | + |
0 commit comments