getting keyboard input 1 char at a time

Michael Hudson mwh21 at cam.ac.uk
Mon Oct 30 09:58:11 EST 2000


"Tim Peters" <tim_one at email.msn.com> writes:

> [John R Bedal]
> > Is there a platform independant method for getting keyboard input one
> > character at a time?
> 
> [Peter Hansen]
> > It's possible John wanted a method which would return "keystrokes", as
> > opposed to just whatever was in stdin.
> > ...
> > On win32, he would have to use msvcrt.getch() or something.
> >
> > I don't think there is a truly platform-independent method, but I'd be
> > happy to be corrected.
> 
> Not your lucky day:  Python doesn't offer a portable way to do this because
> C doesn't (nothing in the std C language or libraries addresses this).  It
> is indeed a x-platform nightmare.  The std getpass.py module is a good one
> to study.
> 
> msvcrt.getch() and getche() work well in Windows, provided you're running in
> a DOS box (not, e.g., in IDLE), and don't try also to read from sys.stdin
> (MS doesn't support mixing console I/O with C stdio -- the results are
> unpredictable if you try).

You can do it easily enough on unix by using curses or mucking with
the termios module, eg:

def read1():
    oldattr = termios.tcgetattr(0)
    try:
        attr = termios.tcgetattr(0)
        attr[3] = attr[3] & ~(TERMIOS.ICANON|TERMIOS.ECHO)
        termios.tcsetattr(0,TERMIOS.TCSANOW,attr)
        while 1:
            return os.read(0,1)
    finally:
        termios.tcsetattr(0,TERMIOS.TCSANOW,oldattr)

Bear in mind that pressing of some keys (eg. arrow keys) can result in
more then one character being transmitted, and that you can make minor
changes to affect what happens when the user presses C-s, C-q, C-c or
enter, whether you want the user's input to be echoed to the screen,
whether you want to wait for a key or just see if the user has pressed
a key, etc.

too-much-freedom?-ly y'rs
m

PS: does anyone know of a reference that explains terminal prgoramming
well?  I can get what I want done by sort of trial and error, but
that's herdly ideal.

-- 
  In case you're not a computer person, I should probably point out
  that "Real Soon Now" is a technical term meaning "sometime before
  the heat-death of the universe, maybe". 
                                     -- Scott Fahlman <sef at cs.cmu.edu>



More information about the Python-list mailing list