getting a key without an echo and Enter

Michael Hudson mwh21 at cam.ac.uk
Sun Apr 2 21:12:28 EDT 2000


"Gang Seong Lee" <gslee111 at daisy.kwangwoon.ac.kr> writes:

> Hi,
> 
> How can I get a key input without having it echoed.
> The following statement echoes and waits until I press Enter key.
> 
> ch = sys.stdin.read(1)
> 
> Can I get the key as soon as I press it without an echo. (No Enter key)
> 
> Thanks in advance

Heh.  I was trying to do this the other day; I came up with the rather
hairy & unix specific:

import termios,TERMIOS,os,select,string,sys

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

On windows, I think some variant of

import msvcrt
msvcrt.getch()

do the job, but I can't test that here.

HTH,
M.

-- 
well, take it from an old hand: the only reason it would be easier
to program in C is that you can't easily express complex  problems
in C, so you don't.                 -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list