Stopping a loop with user input in curses

Dr. Peer Griebel griebel at konzept-is.de
Mon Jul 21 11:00:43 EDT 2003


Alex wrote:
> Hello Ray,
> 
> Nope. That didn't do it. I got a properly drawn curses box
> with nothing inside ... until I hit the 'q' key. Then the clock 
> popped up and the program quit.
> 
> I have a theory on curses. I could be totally wrong here (and it
> would be great if I was, actually).
> 
> Curses cannot multi-task.
> 
> It can't redraw a clock every second and check for a particular
> keystroke at the same time -- there is only one cursor after all.
> 
> So I guess I'll forgoe the funky clock in my curses app. However,
> if you can completely flush this theory down the toilet, it would
> be greatly appreciated... :) It would make my life easier in other
> aspects of the program I'm trying to write.
> 
> 
> Thanks,
> 
> Alex
> 
 >

Try the appended program. You are right, curses does not multi-task. You 
even did not create some task...
But you don't need to have separate tasks. All you have to do is to 
check if keypresses are availabe. And only then you should call getch() 
since it will block until keystrokes are available.
See (to understand you probably have to read documentation aboute select()):


# Import curses module

import curses, time
stdscr = curses.initscr()
from select import select

def theClock():

     # Define global colour scheme
     curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)

     # Get the screen size
     max_y, max_x = stdscr.getmaxyx()

     # Calculate the clock position relative to the screen size
     clock_x = max_x - 28

     # Draw the clock
     clockWindow = curses.newwin(3, 26, 1, clock_x)
     clockWindow.bkgd(' ', curses.color_pair(1))
     clockWindow.box()
     clockWindow.refresh()

     # If 'q' is pressed, exit
     finished = 0
     while not finished:    # finished = 0 until the 'q' key is pressed
         if select([0], [], [], 1)[0]:
             c = stdscr.getch()
             if c == ord('q'):
                 curses.beep()
                 finished = 1
                 break

         t = time.asctime()
         clockWindow.addstr(1, 1, t)
         clockWindow.refresh()


def main(stdscr):

     # Bring up the clock function

     theClock()

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






More information about the Python-list mailing list