[Tutor] Stopping a loop with user input in curses

Lloyd Kvam pythontutor@venix.com
Mon Jul 21 18:18:03 2003


You have two loops in your program.  The first begins:
	while 1:
and is in the theClock function.
This loop will continue forever (1 represents True).  To terminate this
loop you need a break within it.

The send loop is in the main body and begins:
	while 2:
This loop is NEVER executed because you are still executing the first
loop.

You need to move the getch() call into the first loop.  HOWEVER, this
will cause the loop to pause until a key is pressed which is not what
you want.  If you call nodelay(1), then getch() will no longer wait
for the keystroke.  However, now getch() will raise an exception if there
is no keystroke to "get".

The following should help:
     stdscr.nodelay(1) # do not wait for a key press
     while 1:
         t = time.asctime()
         clockWindow.addstr(1, 1, t)
         clockWindow.refresh()
	try:
	    c = stdscr.getch()
	    if c == ord('q'):
		curses.beep()
		break
	except <NeedExceptionName here>: # might be stdscr.error
         	time.sleep(1)

Attempt stdscr.error for the exception name.  If that's wrong, Python
will give you a traceback with the correct name.

There's a tutorial at this link:

http://www.python.org/doc/howto/curses/curses.html

Alex from Caustic Creations wrote:

> Hello all,
> 
> I've written a small clock program in curses that I would
> like to have end when someone presses 'q'. I've included the
> code below. I'm *very* new to python so I apologize in advance if
> this seems like a horribly obvious problem. I've spent all day
> trying various structures but none of them have worked out.
....
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582