Key input that does not wait for key input in Python

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

Key input that does not wait for key input in Python
Key input in Python
Key input in Python
How to judge that the cross key is input in Python3
Processing when the key input of Python pygame does not go well.
Examples and solutions that the Python version specified in pyenv does not run
Search for strings in Python
Python Input Note in AtCoder
Techniques for sorting in Python
Python version does not switch
About "for _ in range ():" in python
[Python] Reason why index error does not occur in slice
[For beginners] Summary of standard input in Python (with explanation)
The story that `while queue` did not work in python
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
Check for memory leaks in Python
Do you want to wait for general purpose in Python Selenium?
Check for external commands in python
A record that GAMEBOY could not be done in Python. (PYBOY)
Problem that discord.py does not break
33 strings that should not be used as variable names in python
Let's see using input in python
Foreign Key in Python SQLite [Note]
Notes for Python file input / output
A special Python codec that seems to know but does not know
Python standard input summary that can be used in competition pro
The story that 2D list replacement did not work in python
Run unittests in Python (for beginners)
Introducing a library that was not included in pip on Python / Windows
python> does not include the letters mm> if "mm" not in text: / print "not including mm"
Get the key for the second layer migration of JSON data in python
[50 counts] Key transmission using Python for Windows
Notes on nfc.ContactlessFrontend () for nfcpy in python
Inject is recommended for DDD in Python
Tips for dealing with binaries in Python
Summary of various for statements in Python
Type annotations for Python2 in stub files!
[VScode] autopep8 format does not work [Python]
Virtualenv does not work on Python3.5 (Windows)
Template for writing batch scripts in python
Python / dictionary> setdefault ()> Add if not in dictionary
Process multiple lists with for in Python
MongoDB for the first time in Python
Python> Python does not include the last offset
Get a token for conoha in python
Sample for handling eml files in Python
tensorflow does not enter in windows + anaconda.
Tkinter could not be imported in Python
AtCoder cheat sheet in python (for myself)
I searched for prime numbers in python
Notes for using python (pydev) in eclipse
In Ruby, inspect does not substitute to_s
Tips for making small tools in python
Use pathlib in Maya (Python 2.7) for upcoming Python 3.7
Atcoder standard input set for beginners (python)
Intuitive explanation that does not rely on mathematical formulas for the Monty Hall problem and simulation with Python
Use something other than a <br> string for the <br> dict key in Python
About the problem that the python version of Google App Engine does not mesh
Collect Japanese tweets that do not include images, URLs or replies in Python
Patch when full text search does not work in GAE / Python local environment
Template for creating command line applications in Python