How to judge that the cross key is input in Python3

Introduction

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

Preface

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

Where it gets stuck

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.

Source

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)

Result of execution

image.png You can see that the judgment has been taken properly.

At the end

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.

reference

Recommended Posts

How to judge that the cross key is input in Python3
How to test that Exception is raised in python unittest
[python] How to check if the Key exists in the dictionary
How to use is and == in Python
To make sure that the specified key is in the specified bucket in Boto 3
How to use the asterisk (*) in Python. Maybe this is all? ..
Key input in Python
Key input in Python
How to use the C library in Python
How to get the files in the [Python] folder
How to get the variable name itself in python
How to get the number of digits in Python
How to know the current directory in Python in Blender
Key input that does not wait for key input in Python
Find the part that is 575 from Wikipedia in Python
How to find the coefficient of the trendline that passes through the vertices in Python
How to use the model learned in Lobe in Python
How to develop in Python
[python] How to judge scalar
[Python] How to output the list values in order
[Python] How to use input ()
How to input a character string in Python and output it as it is or in the opposite direction.
How to check in Python if one of the elements of a list is in another list
How to find the first element that matches your criteria in a Python list
How to debug the Python standard library in Visual Studio
How to use the __call__ method in a Python class
How to get the last (last) value in a list in Python
The story that the private key is set to 600 with chmod
How to collect images in Python
How to use SQLite in Python
In the python command python points to python3.8
How to get the Python version
[python] What is the sorted key?
[Python] How to import the library
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
How to delete "(base)" that appears in the terminal when Anaconda is installed on Mac
[VLC] How to deal with the problem that it is not in the foreground during playback
How is the progress? Let's get on with the boom ?? in Python
Play a sound in Python assuming that the keyboard is a piano keyboard
How to determine the existence of a selenium element in Python
How to give and what the constraints option in scipy.optimize.minimize is
The 15th offline real-time how to write reference problem in Python
The 17th Offline Real-time How to Solve Writing Problems in Python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
The 14th offline real-time how to write reference problem in python
[Beginner memo] How to specify the library reading path in Python
What to do when the value type is ambiguous in Python?
The 18th offline real-time how to write reference problem in Python
How to display bytes in the same way in Java and Python
[Introduction to Python] How to use class in Python?
How to dynamically define variables in Python
How to do R chartr () in Python
How to deal with the problem that the current directory moves when Python is executed from Atom
How to work with BigQuery in Python
How to get a stacktrace in python
How to display multiplication table in python