[PYTHON] Phenomenon that characters disappear when trying to enter one character without Enter

I want to enter one character

The input () function doesn't read unless you hit the enter key. I want to omit pressing the enter key. So I searched for a way to avoid hitting the enter key.

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)

It seems that this can be done for mac Reference source: https://torina.top/detail/428/

Run

while True:
    print('input:',end='')
    key = getch()
    print(key)
#Ends with esc
    if key == chr(27):
        break

The letters disappear!

Input: a
Input: f
[Cursor here]

I was able to ... ** Input: has disappeared! !! ** **

(When I enter one character, it suddenly appears and it feels as if it was there from the beginning)

Target

input:[Cursor here]

I want you to be

Conclusion

while True:
    print('\r input:',end='')
    key = getch()
    print(key)
    if key == chr(27):
        break

If you do it in the place where you don't want to erase \ r,input:did not disappear! !! I'm not sure why, but it's the result of trial and error. Apparently, you should put characters such as \ r and \ n in the string before getch ().

It seems that it is necessary to force the output (addition)

print('key :', end='', flush=True)

I was able to display it. Everything is not reflected on the screen until the line break is output, If you do print ('key:', end ='') somewhere else, it will be output without line breaks, so it's a mess. ..

I think I can do various things with this

s = []
while 1:
    print('\r'+''.join(s), end='')
    char = getch()
#Ends with esc
    if char == chr(27):
        break
#When you press enter\Is r entered? Ignore because the cursor is at the left end
    elif char == chr(13):
        continue
#Delete one character with backspace
    elif char == chr(127):
        if len(s) != 0:
            s.pop()
            print('\b ',end='')
        continue
    s.append(char)
print('')

Now I'm typing one character at a time, but I was able to display it each time! If you add a little more processing, you can convert from lowercase to uppercase at the same time you hit it! Wow!

Recommended Posts

Phenomenon that characters disappear when trying to enter one character without Enter
[GNOME] How to avoid the problem that conversion candidate characters do not disappear when converting to Japanese
Memorandum Regular expression When there are multiple characters in the character string that you want to separate
UnicodeEncodeError when trying to run radon
A story that suffered from OS differences when trying to implement a dissertation