我正在 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/