0

How to catch special keypress in Python 3.4.3 Ubuntu Console?
I found this:

import tty, sys, termios, select
def setup_term(fd, when=termios.TCSAFLUSH):
    mode = termios.tcgetattr(fd)
    mode[tty.LFLAG] = mode[tty.LFLAG] & ~(termios.ECHO | TERMIOS.ICANON)
    termios.tcsetattr(fd, when, mode)
def getch(timeout=None):
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        setup_term(fd)
        try:
            rw, wl, xl = select.select([fd],[],[],timeout)
        except select.error:
            return
        if rw:
            return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

but it doesn't detect press of F1, Alt, Ctrl, and similar.
I would like to not adding any packages, if it's possible.

sorry for my English

vakus
  • 732
  • 1
  • 10
  • 24

1 Answers1

1

Using the curses module might help you if you want to build a text user interface. This example prints a key code for each pressed key:

import curses

def main(stdscr):
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)
    while True:
        keycode=stdscr.getch()
        stdscr.addstr("%i\n" % keycode)
        stdscr.refresh()

curses.wrapper(main)

For special keys like F1, enter or arrow keys, compare the key code with some of the constants like curses.KEY_F1: https://docs.python.org/3/library/curses.html#constants

You will not be able to capture some modifier keys like alt or control though. This is not possible with regular terminals, see How to get CTRL, Shift or Alt with getch() ncurses?

Community
  • 1
  • 1
Morn
  • 36
  • 2