Python curses dilemma

math4tots picture math4tots · Mar 24, 2012 · Viewed 11.2k times · Source

I'm playing around a little with Python and curses.

When I run

import time
import curses

def main():
    curses.initscr()
    curses.cbreak()
    for i in range(3):
        time.sleep(1)
        curses.flash()
        pass
    print( "Hello World" )
    curses.endwin()

if __name__ == '__main__':
    main()

if I wait all the way through, curses.endwin() gets called so everything works out fine. However, if I cut it short with Ctrl-C, curses.endwin() never gets called so it screws up my terminal session.

What is the proper way to handle this situation? How can I make sure that no matter how I try to end/interrupt the program (e.g. Ctrl-C, Ctrl-Z), it doesn't mess up the terminal?

Answer

Henrik Lindgren picture Henrik Lindgren · Feb 17, 2013

I believe you are looking for curses.wrapper See http://docs.python.org/dev/library/curses.html#curses.wrapper

It will do curses.cbreak(), curses.noecho() and curses_screen.keypad(1) on init and reverse them on exit, even if the exit was an exception.

Your program goes as a function to the wrapper, example:

def main(screen):
    """screen is a curses screen passed from the wrapper"""
    ...

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