DCA- DCA- - 1 year ago 141
Python Question

Python key binding/capture

I'd like to know the simplest way to bind keys in python

for example, the default python console window apears and waits, then in psuedo ->

if key "Y" is pressed:
print ("Yes")
if key "N" is pressed:
print ("No")

I would like to achieve this without the use of any modules not included by python. just pure python

Any and all help is greatly appreciated

python 2.7 or 3.x Windows 7

requires the user to hit enter and is therefore not keybinding

Answer Source

From http://code.activestate.com/recipes/134892/ (although a bit simplified):

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
    def __init__(self):
        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)
            ch = sys.stdin.read(1)
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

getch = _Getch()

Then you can do:

>>> getch()
'Y' # Here I typed Y

This is great as it doesn't need any 3rd party modules.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download