Python input() does not detect EOL in MINGW terminal (but does in CMD terminal)

302 views Asked by At

I'm running the following program in python 3.5.2 in Windows 10:

username = input('uname:')

If I run in a MINGW terminal, the input() function offers a prompt, but fails to return after I type some text followed by <RETURN> key.

Running the same program in a command(cmd.exe) terminal, the input() returns with a string as expected.

I suspect this is to do with different EOL representations in Windows vs MinGW. I've tried spoofing a windows EOL by typing ^M <RETURN> to no avail.

Ideally I would like to solve this problem 'in-script' and make it transparent to the user, but failing that I would like some solution, even if in means the user has to type some magic key-combo.

BTW, the same problem (not detecting EOL) occurs if I run the script in the Visual Studio Code python debugger.

1

There are 1 answers

0
Dan Gonzalez On

I recently had a similar issue.

After some looking around, I ended up ditching input and going with something like this, which checks ordinance of endline chars (based on this answer):

import sys
import os

try:
    # Win32
    from msvcrt import getch
except ImportError:
    # UNIX
    import tty
    import termios

    def getch():
        # print('READING!')
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
            sys.stdout.write(ch)
            sys.stdout.flush()
            return ch
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)

input = []

while True:
    char = getch()
    input.append(char)

    # crtl + c
    if ord(char) == 3:
        print('input: {}'.format(''.join(input)))
        sys.exit()
    # \n
    elif ord(char) == 10:
        print('input: {}'.format(''.join(input)))
        sys.exit()
    # \r
    elif ord(char) == 13:
        print('input: {}'.format(''.join(input)))
        sys.exit()
    elif ord(char) == ord(os.linesep):
        print('input: {}'.format(''.join(input)))
        sys.exit()