Function keys and cursor keys can also be identified. It is not possible to judge the single input of the Shift key or Control key, but the simultaneous pressing with the character key can be identified. When the termios.ISIG mask is enabled, Cntl + C accepts the program as a key input without stopping.
point
--Disable echo in termios, disable canonical mode --Set to NONBLOCK mode with fcntl
getkey.py
import fcntl
import termios
import sys
import os
def getkey():
fno = sys.stdin.fileno()
#Get stdin terminal attributes
attr_old = termios.tcgetattr(fno)
#Stdin echo disabled, canonical mode disabled
attr = termios.tcgetattr(fno)
attr[3] = attr[3] & ~termios.ECHO & ~termios.ICANON # & ~termios.ISIG
termios.tcsetattr(fno, termios.TCSADRAIN, attr)
#Set stdin to NONBLOCK
fcntl_old = fcntl.fcntl(fno, fcntl.F_GETFL)
fcntl.fcntl(fno, fcntl.F_SETFL, fcntl_old | os.O_NONBLOCK)
chr = 0
try:
#Get the key
c = sys.stdin.read(1)
if len(c):
while len(c):
chr = (chr << 8) + ord(c)
c = sys.stdin.read(1)
finally:
#Undo stdin
fcntl.fcntl(fno, fcntl.F_SETFL, fcntl_old)
termios.tcsetattr(fno, termios.TCSANOW, attr_old)
return chr
if __name__ == "__main__":
while 1:
key = getkey()
#Exit with enter, display if there is a key input
if key == 10:
break
elif key:
print(key)
Recommended Posts