Neither input
or sys.stdout.read
will be enough to read character by character without the proper EOL. For this you will have to work at a lower level with the terminal on duty. In Windows you can use the module msvcrt
and the functions getch
, getche
, getwch
and getwche
:
import msvcrt
palabra = []
while True:
letra = msvcrt.getwche()
if letra == '.':
break
else:
palabra.append(letra)
print("\n" + "".join(palabra))
On POSIX you can use termios
:
import os
import sys
import termios
file_descriptor = sys.stdin.fileno()
old = termios.tcgetattr(file_descriptor)
new = old[:]
palabra = []
try:
new[3] &= ~(termios.ICANON | termios.ECHOCTL)
termios.tcsetattr(file_descriptor, termios.TCSADRAIN, new)
while True:
letra = sys.stdin.read(1)
if letra == '.':
break
else:
palabra.append(letra)
finally:
termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old)
print("\n" + "".join(palabra))
In both cases the character is printed when it is entered, although we can make it not so if we want it:
- On Windows, change
msvcrt.getwche
by msvcrt.getwch
.
-
In POSIX change the line:
new[3] &= ~(termios.ICANON | termios.ECHOCTL)
by:
new[3] &= ~(termios.ICANON | termios.ECHO)
Note: The script will run directly on the system terminal. Normally it will not work in the terminal or interactive interpreter of the IDE of turn.