Keypress Input

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Jun 15 07:22:13 EDT 2015


On 15 June 2015 at 06:23, John McKenzie <davros at bellaliant.net> wrote:
>
>  Thank to the others who joined in and posted replies.
>
>  Michael, your assumption is correct. To quote my original post, "and I
> want this working on a Raspberry Pi." Doing a superficial look at curses
> and getch it looks excessively complicated. I was under the impression it
> was not multi-platform and Linux was excluded. Searching for getch and
> raspberry pi on the web I see it is not and is available for Raspian.

I'm not sure what you mean but you can write a getch function for
Unixy systems using the tty module (I can't remember where I
originally borrowed this code from):

import sys, tty, termios

def getch():
    fd = sys.stdin.fileno()
    oldsettings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
    return c

while True:
    key = getch()
    print("key: '%c'  code: '%d'" % (key, ord(key)))
    if key == 'q':
        break

This puts the terminal in "raw mode" and waits for a key-press. Once a
key is pressed the terminal is restored to it's previous mode (most
likely not raw mode) and the character is returned. This is important
because once your program finishes you don't want the terminal to be
in raw mode. If the terminal goes weird you can usually fix it by
typing "reset" and pressing enter.

Note that going into raw mode has other implications such as not being
able to exit your program with ctrl-c or suspend with ctrl-z etc. You
can explicitly process those kinds of contrl keys with something like:

while True:
    key = getch()
    if 1 <= ord(key) <= 26:
        ctrl_key = chr(ord(key) + 64)
        print("ctrl-%c" % ctrl_key)
        if ctrl_key == 'C':
            break
    else:
        print("key: '%c'" % key)


--
Oscar



More information about the Python-list mailing list