[Tutor] A little help please

alan.gauld@bt.com alan.gauld@bt.com
Wed, 26 Dec 2001 16:27:06 -0000


> 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.  

There is no portable way of doing this(*) in standard Python but
you can do it by using two distinct modules:

msvcrt for Windows and curses for Linux

They both have similar getch() functions and you could test 
for the OS at the top of the function. Something like:

def getkey():
   if os == windows or NT or DOS:
      return msvcrt.getch()
   elif os == posix:
      return curses.wgetch()
   else: return raw_input()  # don't know how to read instant keys...

I suspect you will need to write an init function for the 
curses stuff to set up the virtual screen that cureses uses.

Note that the functions will wait for input (ie not like 
BASIC INKEY$) but do not wait for an ENTER key.

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

To get the -1 for no key hit you will need to do something 
clever to arrange a timeout.... Maybe launching a thread 
then killing it after a delay, thats getting trickier...

> of this function would be function keys.  

The msvcrt.getch works with function keys etc, I don't 
remember how curses.wgetch works.

You might like to take a peek at my online tutor under 
Event Driven programming to see an example, if you can 
find a copy of my book even better since it shows 
msvcrt.getch in action.


HTH,

Alan G.

(*) Fred Lundh has a console module that tries to be OS 
independant but I can't recall if it has a getch function.