我写了一个接受一个字符的函数(没有点击enter
),并检查验证,并返回按下的键。但问题是,如果值不匹配,我打印的提示是打印两次。这是我的代码。
def accept_input():
while True:
print "Type Y to continue, ctrl-c to exit"
ch = sys.stdin.read(1)
if ch != "Y":
pass
else:
return ch
当调用accept_input()
时,如果有不匹配的字符,它会打印提示两次,如果输入为空,则打印一次。
python accept_input.py
Type Y to continue, ctrl-c to exit
a
Type Y to continue, ctrl-c to exit
Type Y to continue, ctrl-c to exit
b
Type Y to continue, ctrl-c to exit
Type Y to continue, ctrl-c to exit
c
Type Y to continue, ctrl-c to exit
Type Y to continue, ctrl-c to exit
Type Y to continue, ctrl-c to exit
Type Y to continue, ctrl-c to exit
Y
accepted
输入任何非匹配键时,为什么打印两次?为什么输入空白键时只打印一次?
感谢。
答案 0 :(得分:2)
那是因为a
之后你也按了\n
...所以2个字符。你可以清除缓冲区了。
def accept_input():
import sys
while True:
print "Type Y to continue, ctrl-c to exit"
ch = sys.stdin.read(1)
sys.stdin.flush() #<===========
if ch != "Y":
pass
else:
return ch