How to input one char at a time from stdin?

B

Brent W. Hughes

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?

Brent
 
S

Swaroop C H

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"

This recipe was a lifesaver for me once :)

Regards,
 
J

John Machin

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'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top