blob: 3cdaa82d0a856e2b18b480ffbaee646af77ebe73 [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
Christian Heimes05e8be12008-02-23 18:30:17 +000010import curses
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000011
Michael W. Hudson09ad2352004-08-07 15:18:07 +000012def wrapper(func, *args, **kwds):
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000013 """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 """
Guido van Rossumbffa52f2002-09-29 00:25:51 +000019
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000020 try:
Guido van Rossumbffa52f2002-09-29 00:25:51 +000021 # Initialize curses
Georg Brandl07b90ca2010-08-02 19:44:48 +000022 stdscr = curses.initscr()
Guido van Rossumbffa52f2002-09-29 00:25:51 +000023
24 # Turn off echoing of keys, and enter cbreak mode,
25 # where no buffering is performed on keyboard input
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000026 curses.noecho()
27 curses.cbreak()
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000028
Guido van Rossumbffa52f2002-09-29 00:25:51 +000029 # 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
Andrew M. Kuchlingd0939fa2000-06-10 23:06:53 +000032 stdscr.keypad(1)
33
Eric S. Raymond1ebd3f62000-08-09 21:11:07 +000034 # Start color, too. Harmless if the terminal doesn't have
35 # color; user can test with has_color() later on. The try/catch
36 # works around a minor bit of over-conscientiousness in the curses
37 # module -- the error return from C start_color() is ignorable.
38 try:
39 curses.start_color()
40 except:
41 pass
42
Michael W. Hudson3fdd43e2004-08-07 15:20:15 +000043 return func(stdscr, *args, **kwds)
Michael W. Hudson09ad2352004-08-07 15:18:07 +000044 finally:
Guido van Rossumbffa52f2002-09-29 00:25:51 +000045 # Set everything back to normal
Jeremy Hylton2ea17fa2000-07-07 21:02:22 +000046 stdscr.keypad(0)
47 curses.echo()
48 curses.nocbreak()
Michael W. Hudson09ad2352004-08-07 15:18:07 +000049 curses.endwin()