【问题标题】:Python input() does not detect EOL in MINGW terminal (but does in CMD terminal)Python input() 未检测到 MINGW 终端中的 EOL(但在 CMD 终端中检测到)
【发布时间】:2016-12-14 14:13:10
【问题描述】:

我在 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)。

【问题讨论】:

    标签: python mingw eol


    【解决方案1】:

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

    环顾四周后,我最终放弃了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()
    

    【讨论】:

      猜你喜欢
      • 2013-09-02
      • 2014-09-11
      • 1970-01-01
      • 2021-12-04
      • 2010-09-20
      • 2021-03-25
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      相关资源
      最近更新 更多