【问题标题】:Python sys.stdin.read() accept input condition print prompt twicePython sys.stdin.read() 两次接受输入条件打印提示
【发布时间】:2023-04-10 22:46:01
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: python user-input stdin sys


    【解决方案1】:

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

    【讨论】:

    • Thankyou @vks,但提示的重复打印仍然存在。输入任意字符,"Type Y to continue, ctrl-c to exit" 行会打印两次。
    • @nohup 你确定你复制了我的代码吗?因为如果我只在打印type Y 行时输入a
    • 是的。准确的副本。我刚刚更正了最初的缩进。同时,我还有一个问题。这个函数的目的,即在没有输入的情况下接受输入,从一开始就不起作用。我做错了什么?
    • 如你所说,如果我输入多个字符,如abc,它会迭代并打印4次(包括\n)。我正在使用Python 2.7.9
    • @nohup 可能会有所帮助stackoverflow.com/questions/3523174/…
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多