Python sys.stdin.read(1) in a while(True) loop consistently executes 1 time getting input and multiple times not getting input

前端 未结 2 1243
长发绾君心
长发绾君心 2021-01-27 00:01

I\'m running python 2.7 on 64-bit Windows 7.

Here is the code i\'m executing:

import sys
while True:
    print \'please enter a character:\'
    c = sys.         


        
相关标签:
2条回答
  • 2021-01-27 00:20

    sys.stdin is line-buffered by default i.e., your sys.stdin.read(1) won't return until there is full line in stdin buffer.

    It means if you enter a character and hit Enter then after you get the first character with sys.stdin.read(1), there is a newline in the buffer (one or two characters: os.linesep) that are read immediately on the next loop iterations.

    You could avoid hitting Enter by reading exactly one character at a time (msvcrt.getch()).

    0 讨论(0)
  • 2021-01-27 00:36

    Problem is probably due to flushing of stdin since the \n lingers on.

    as an alternative, use raw_input

    while True:
        c = raw_input('please enter a character: ')
        print 'you entered', c
    

    For the flushing part, see this

    0 讨论(0)
提交回复
热议问题