code: def curses_session():
      
  
      try:
          # Curses must wait for some time after the Escape key is pressed to
          # check if it is the beginning of an escape sequence indicating a
          # special key. The default wait time is 1 second, which means that
          # http://stackoverflow.com/questions/27372068
          os.environ['ESCDELAY'] = '25'
  
          # Initialize curses
          stdscr = curses.initscr()
  
          # Turn off echoing of keys, and enter cbreak mode, where no buffering
          # is performed on keyboard input
          curses.noecho()
          curses.cbreak()
  
          # In keypad mode, escape sequences for special keys (like the cursor
          # keys) will be interpreted and a special value like curses.KEY_LEFT
          # will be returned
          stdscr.keypad(1)
  
          # Start color, too.  Harmless if the terminal doesn't have color; user
          # can test with has_color() later on.  The try/catch works around a
          # minor bit of over-conscientiousness in the curses module -- the error
          # return from C start_color() is ignorable.
          try:
              curses.start_color()
              curses.use_default_colors()
          except:
              _logger.warning('Curses failed to initialize color support')
  
          # Hide the blinking cursor
          try:
              curses.curs_set(0)
          except:
              _logger.warning('Curses failed to initialize the cursor mode')
  
          yield stdscr
  
      finally:
          if 'stdscr' in locals():
              stdscr.keypad(0)
              curses.echo()
              curses.nocbreak()
              curses.endwin()
docs: Setup terminal and initialize curses. Most of this copied from
      curses.wrapper in order to convert the wrapper into a context manager.