[Tutor] curses.wrapper() question

Michael Janssen Janssen@rz.uni-frankfurt.de
Thu Jul 17 18:37:03 2003


On Thu, 17 Jul 2003, Alex from Caustic Creations wrote:

> Hello,
>
> I'm trying to learn python because I would like to create a simple cash
> register application using curses. I read the curses howto and the
> reference manual and both refer to the curses.wrapper function. The
> advantages of using the wrapper are significant, yet I can't seem to
> call it up properly.
>
> I've included my "test.py" program - a compilation of all of the
> statements in the curses howto so I could see and play around with their
> effects. If anyone can find the time, could someone alter this little
> demo program using the curses wrapper to illustrate its correct use?

Hi Alex,

curses.wrapper() is very easy to use :-) But you have to redesign your
script for this....

curses.wrapper takes a function as argument. But what for a function? The
"main" function for your curses application that does *all* the logic.

By now you write your script much like a shell-script doing one step after
another. This is a typical way to start, not that efficient (in terms of
maintainable code) and unfortunatelly a no-go-way for curses.wrapper.

A better design would be:

1. setting some global constants (if at all)

2. definining a "main" function (you can call it at wil, but "main" is
often used) that does all the logic (mostly by calling subfunctions)

3. define subfunctions as you need

4. call "main":

main()

This should (should in the meanding of "for the sake of beauty") be the
only piece of code that is called on top level (zero indentation).

curses.wrapper is now simply used this way:
curses.wrapper(main)

Here I've got a piece of code that shows the non-wrapper way but with use
of a "main" function (The "if __name__=='__main__':" part asures that the
code is only excecuted when the file is excecuted as a script (not
imported as a modul). You can ignore this when you can't see the
benefit. try-finally asures the the finally-block is executed even if an
exception occurs in main. You shouldn't ignore this ;-):

if __name__=='__main__':
    try:
	stdscr=curses.initscr()
	curses.noecho() ; curses.cbreak()
	stdscr.keypad(1)
	main(stdscr)			# Enter the main loop
    finally:
        stdscr.erase()
        stdscr.refresh()
	stdscr.keypad(0)
	curses.echo() ; curses.nocbreak()
	curses.endwin()			# Terminate curses


and the same (plus color activating) with the wrapper:

if __name__=='__main__':
    curses.wrapper(main)


When you absolutly have no idea how to break your code into subfunctions
and call them by a main-function, then you can also add one level of
indentation to the whole code and put a
def main():

right in front of it. As a last resort ;-)

cheers
Michael