How to input one char at a time from stdin?
John Machin
sjmachin at lexicon.net
Tue Jan 25 17:47:09 EST 2005
On Wed, 26 Jan 2005 01:15:10 +0530, Swaroop C H <swaroopch at gmail.com>
wrote:
>On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes
><brent.hughes at comcast.net> wrote:
>> I'd like to get a character from stdin, perform some action, get another
>> character, etc. If I just use stdin.read(1), it waits until I finish typing
>> a whole line before I can get the first character. How do I deal with this?
>
>This is exactly what you need:
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
>Title: "getch()-like unbuffered character reading from stdin on both
>Windows and Unix"
Nice to know how, but all those double underscores made my eyes bleed.
Three classes? What's wrong with something simple like the following
(not tested on Unix)?
import sys
bims = sys.builtin_module_names
if 'msvcrt' in bims:
# Windows
from msvcrt import getch
elif 'termios' in bims:
# Unix
import tty, termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
else:
raise NotImplementedError, '... fill in Mac Carbon code here'
More information about the Python-list
mailing list