Python input() 在 MINGW 终端中不检测 EOL(但在 CMD 终端中检测)

标签 python mingw eol

我正在 Windows 10 中的 python 3.5.2 中运行以下程序:

username = input('uname:')

如果我在 MINGW 终端中运行,input()函数提供了提示,但在我输入一些文本后无法返回 <RETURN>关键。

在命令(cmd.exe)终端中运行相同的程序,input()按预期返回一个字符串。

我怀疑这与 Windows 和 MinGW 中不同的 EOL 表示有关。我尝试通过输入 ^M <RETURN> 来欺骗 Windows EOL没有效果。

理想情况下,我想“在脚本中”解决这个问题并使其对用户透明,但如果做不到这一点,我想要一些解决方案,即使这意味着用户必须输入一些神奇的组合键。

顺便说一句,如果我在 Visual Studio Code python 调试器中运行脚本,也会出现同样的问题(未检测到 EOL)。

最佳答案

我最近遇到了类似的问题。

环顾四周后,我最终放弃了 input 并采用了类似的方法,它检查结束行字符的条例(基于 this 答案):

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()

关于Python input() 在 MINGW 终端中不检测 EOL(但在 CMD 终端中检测),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41144737/

相关文章:

python - 对字符串中与正则表达式模式不匹配的所有部分进行操作的函数

python - Pandas 填补时间序列中缺失的日期

c++ - 找不到 -lbgi 和 ld 返回 1 个退出状态错误

c - 未初始化的字符数组

c - 如何在C中读取数字到字符串直到行尾

python - 在 CentOS 上为 Python3 编译 C 扩展

python - 使用 OpenCV 图像的 Flask 视频流

c - 如何在 MinGW 中使用预编译静态库?

python - 如何防止 django 表单删除换行符

c++ - 选择 Qt 写入文本文件的自定义行结尾