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

前端 未结 2 1242
长发绾君心
长发绾君心 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()).

提交回复
热议问题