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/
while True:
print('input:',end='')
key = getch()
print(key)
#Ends with esc
if key == chr(27):
break
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)
input:[Cursor here]
I want you to be
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 ()
.
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. ..
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