wrapper.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """curses.wrapper
  2. Contains one function, wrapper(), which runs another function which
  3. should be the rest of your curses-based application. If the
  4. application raises an exception, wrapper() will restore the terminal
  5. to a sane state so you can read the resulting traceback.
  6. """
  7. import sys, curses
  8. def wrapper(func, *args, **kwds):
  9. """Wrapper function that initializes curses and calls another function,
  10. restoring normal keyboard/screen behavior on error.
  11. The callable object 'func' is then passed the main window 'stdscr'
  12. as its first argument, followed by any other arguments passed to
  13. wrapper().
  14. """
  15. res = None
  16. try:
  17. # Initialize curses
  18. stdscr=curses.initscr()
  19. # Turn off echoing of keys, and enter cbreak mode,
  20. # where no buffering is performed on keyboard input
  21. curses.noecho()
  22. curses.cbreak()
  23. # In keypad mode, escape sequences for special keys
  24. # (like the cursor keys) will be interpreted and
  25. # a special value like curses.KEY_LEFT will be returned
  26. stdscr.keypad(1)
  27. # Start color, too. Harmless if the terminal doesn't have
  28. # color; user can test with has_color() later on. The try/catch
  29. # works around a minor bit of over-conscientiousness in the curses
  30. # module -- the error return from C start_color() is ignorable.
  31. try:
  32. curses.start_color()
  33. except:
  34. pass
  35. return func(stdscr, *args, **kwds)
  36. finally:
  37. # Set everything back to normal
  38. stdscr.keypad(0)
  39. curses.echo()
  40. curses.nocbreak()
  41. curses.endwin()