Ich war auf der Suche nach einer Funktion zum Auslesen der Tastatur in einer Konsolenanwendung. Das Hauptprogramm lief in einer Schleife und ich benötigte eine nicht blockierende Funktion für die Tastatur. Dabei bin ich auf einen Code gestoßen, den ich wie folgt angepasst habe:
# Keyboard.py
import termios
import fcntl
import sys
import os
class Keyboard(object):
__old_term = None
__old_flags = None
__fd = None
__instance = None
@staticmethod
def get_instance():
if Keyboard.__instance is None:
Keyboard()
return Keyboard.__instance
def __init__(self):
if Keyboard.__instance is not None:
raise Exception("This class is a singleton")
else:
Keyboard.__instance = self
self.__fd = sys.stdin.fileno()
self.__old_term = termios.tcgetattr(self.__fd)
new_attr = termios.tcgetattr(self.__fd)
new_attr[3] = new_attr[3] \
& ~termios.ICANON \
& ~termios.ECHO
termios.tcsetattr(self.__fd, termios.TCSANOW, new_attr)
self.__old_flags = fcntl.fcntl(self.__fd, fcntl.F_GETFL)
fcntl.fcntl(self.__fd, fcntl.F_SETFL,
self.__old_flags | os.O_NONBLOCK)
@staticmethod
def read_key():
return sys.stdin.read(1)
def dispose(self):
termios.tcsetattr(self.__fd, termios.TCSAFLUSH,
self.__old_term)
fcntl.fcntl(self.__fd, fcntl.F_SETFL, self.__old_flags)
Der hier beschriebene Quellcode benötigt eine „echte“ Terminal-Konsole. Damit der Code beispielsweise in PyCharm funktioniert, muss folgende Einstellung vorgenommen werden:
- Menü Run und dann Edit configurations…
- Unterhalb von Python ist das entsprechende Projekt auszuwählen
- Die Auswahl Emulate terminal in output console aktivieren.
Die Komponente ist als Singleton implementiert. Die Verwendung sieht folgendermaßen aus:
# main.py
from Keyboard import Keyboard
def main():
keyboard = Keyboard.get_instance()
quit_app = False
try:
while not quit_app:
try:
key = keyboard.read_key()
if key is not None:
if key == 'q':
quit_app = True
print("Auf wiedersehen.")
if key == 'n':
# Do something
except IOError:
pass
finally:
keyboard.dispose()
if __name__ == '__main__':
main()
Damit ist ein einfaches Auslesen der Tastatur möglich.