[Tutor] A little help please

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 25 Dec 2001 12:02:31 -0800 (PST)


On Mon, 24 Dec 2001, nova812 wrote:

> I'm in need of a function that will work on both a linux box and a
> windows box that, from the command line, will detect a key hit on the
> keyboard.

If it were only Linux, I'd recommend the "curses" module:

    http://www.python.org/doc/lib/module-curses.html

However, I'm not sure how successfully the 'curses' module works on
Windows systems.  There's an introductory article on curses here:

    http://www-106.ibm.com/developerworks/linux/library/l-python6.html


> the function should return -1 for no key hit detected and the ascii
> code for any other key hit.

This is possible to do.  By default, if no key hasn't been hit yet, the
getch() function raises an exception, but we can write a small wrapper
function that does something more reasonable.


###
import curses
stdscr = curses.initscr()
curses.cbreak()

def getKey():
    try:
        return stdscr.getch()
    except:
        return -1
###


Good luck!