Skip to main content
 首页 » 编程设计

Python sys.stdin.read()接受输入条件打印提示两次

2024年10月24日13kuangbin

我编写了一个函数,它接受一个字符(无需点击 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 

为什么输入任何不匹配的键都打印两次,为什么输入空白键只打印一次?

谢谢。

请您参考如下方法:

那是因为在 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