Enter characters continuously in the terminal without pressing Enter

0

I would like to create a program that would read characters entered by the user but continuously, without having to press Enter every time I type one and stop reading, for example, when entering a '.'

Something like:

palabra = []

while True:
    letra = input()
    if letra == '.':
        break
    else:
        palabra.append(letra)
    
asked by Alex Gubia 15.04.2018 в 21:49
source

1 answer

1

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.

    
answered by 15.04.2018 в 23:55