2

I wrote a function that accepts a character (without hitting enter), and checks for validation, and returns the key pressed. But the problem is, the prompt I am printing is printing it two times if the value is not matched. Here is my code.

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

and when called accept_input(), it is printing the prompt twice when there is a non matching character, and printing once if the input is blank.

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

Why is it printing twice when entering any non matching key, and why is it printing only once when a blank key is entered?

Thanks.

EdenSource
  • 3,387
  • 16
  • 29
nohup
  • 3,105
  • 3
  • 27
  • 52

1 Answers1

2

That's because after a you pressed \n too...so 2 characters.You can clear the buffer instead.

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
vks
  • 67,027
  • 10
  • 91
  • 124
  • Thankyou @vks, but the repeated printing of the prompt is still there. You enter any character, and the line `"Type Y to continue, ctrl-c to exit"` is printed twice. – nohup Oct 14 '15 at 09:23
  • @nohup r u sure you copied my code? coz for me if i type `a` only once the line `type Y` is getting printed. – vks Oct 14 '15 at 09:27
  • Yep. Exact copy. I just corrected the indentation from the initial one. Meanwhile, I have one more question. The purpose of this function, that is to accept input without an enter, was not working from the initial time. What am I doing wrong? – nohup Oct 14 '15 at 09:39
  • As you said, if I enter multiple characters, like `abc`, it iterates it and prints 4 times (including `\n`). I'm using `Python 2.7.9` – nohup Oct 14 '15 at 09:42
  • @nohup at my end it is not printing for `\n`.If you enter `abc` only `2` times the `line` is printed.the function is working as expected exlcuding `\n` from input.... – vks Oct 14 '15 at 09:44
  • 1
    @nohup may be this could help http://stackoverflow.com/questions/3523174/raw-input-in-python-without-pressing-enter – vks Oct 14 '15 at 09:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92236/discussion-between-nohup-and-vks). – nohup Oct 14 '15 at 09:48