0

I'm trying to create a commandline remote control in python (running on OSX) that responds to individual key presses. So far, with the help of this old SO I've gotten as far as being able to identify and respond to most key presses, but I'd like to give a meaning to the enter key as well.

Unfortunately, I can't find anything like a key code for the enter key.

Failing code:

import sys, 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

keymaps = {"A": "UP",
           "B": "DOWN",
           "C": "RIGHT",
           "D": "LEFT"}

while True:
    char = getch()
    if char == 'q':
        break
    elif char == '[':
        char2 = getch()
        print(keymaps.get(char2, "keycode not found"))
    elif char == '\n':
        print("ENTER")
    else:
        print(char)

when I run this, everything (echoing characters, printing directions) works except that pressing enter just prints a blank space rather than, say, the word "ENTER". I've also tried swapping \n out for the empty string, but that still fails.

How do I identify the enter key?

Paul Gowder
  • 2,409
  • 1
  • 21
  • 36

0 Answers0