You can determine the key by using the curses module. Here's a method that doesn't depend on it https://docs.python.org/ja/3/library/curses.html#constants
This is a memo for myself. It's a straightforward implementation. What I want to do is detect that a special character such as the cross key has been entered.
Knowledge of Unicode control characters is desirable as a prerequisite. wikipedia
getch gets the input character by character. However, the arrow keys had to be entered three times. For example, the up arrow says 27 91 65
. If nothing is done, not only will it not be possible to determine special keys such as arrow keys, but it will also receive unwanted input. Therefore, I implemented it as follows.
getch Function that accepts one-character input ord is a function that converts characters to Unicode, chr is a function that converts Unicode to characters. The code is redundant, which doubles as a debug for myself.
#Prepare a function that receives input character by character instead of input.
#try for Windows, except Nonaka for Linux
try:
from msvcrt import getch
except ImportError:
import sys
import tty
import termios
def getch():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
#Unicode control character aliases
EOT = 3
TAB = 9
ESC = 27
#Main loop
while True:
key = ord(getch())
if key == EOT:
break
elif key == TAB:
print('keydown TAB')
elif key == ESC:
key = ord(getch())
if key == ord('['):
key = ord(getch())
if key == ord('A'):
print('keydown uparrow')
continue
elif key == ord('B'):
print('keydown downarrow')
continue
elif key == ord('C'):
print('keydown leftarrow')
continue
elif key == ord('D'):
print('keydown rightarrow')
continue
else:
message = f'keydown {chr(key)}'
print(message)
You can see that the judgment has been taken properly.
This time, I didn't implement it because the code becomes redundant, but if you look at the Unicode when you enter a special key and enumerate all of them with conditional branching, you can make a judgment. The similar code in this article may be useful when building your own application. If anyone else knows a good way to write, please let me know.
Recommended Posts