tags:

views:

2944

answers:

3

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned. Sort of like getch(). I know that there is a function in windows for it, but I'd like something that is cross-platform.

Thanks.

+7  A: 

Here's a link to a site that says how you can read a single character in both windows and linux:http://code.activestate.com/recipes/134892/.

tehvan
code seems short enough that you could just include it, but +1 for finding a good (cross-platform) answer so quickly.
John Mulder
+5  A: 
sys.stdin.read(1)

will basically read 1 byte from STDIN.

If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:

class _Getch:
"""Gets a single character from standard input.  Does not echo to the screen."""
def __init__(self):
    try:
        self.impl = _GetchWindows()
    except ImportError:
        self.impl = _GetchUnix()

def __call__(self): return self.impl()


class _GetchUnix:
def __init__(self):
    import tty, sys

def __call__(self):
    import sys, tty, termios
    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


class _GetchWindows:
def __init__(self):
    import msvcrt

def __call__(self):
    import msvcrt
    return msvcrt.getch()


getch = _Getch()

(taken from http://code.activestate.com/recipes/134892/)

Yuval A
I find it odd that sys.stdin.read(1) waits for a \n, lol. Thanks for the submission, though.
Evan Fosmark
One character or one byte? That's not the same.
chryss
@Evan, that's because python is in line buffered mode by default
gnibbler
+2  A: 

I think it gets extremely clunky at this point, and debugging on the different platforms is a big mess.

You'd be better off using something like pyglet, pygame, cocos2d - if you are doing something more elaborate than this and will need visuals, OR curses if you are going to work with the terminal.

Curses is standard: http://docs.python.org/library/curses.html

nachik