sys.stdin.readline() reads without prompt, returning 'nothing in between'

lightandlight picture lightandlight · Jan 13, 2014 · Viewed 124.8k times · Source

I have a function that executes the following (among other things):

userinput = stdin.readline()
betAmount = int(userinput)

Is supposed to take input integer from stdin as a string and convert it to an integer.

When I call the function, however, it returns a single newline character (it doesn't even wait for me to input anything).

Earlier in the program I get some input in the form of:

stdin.read(1)

to capture a single character.

Could this have something to do with it? Am I somehow writing a newline character to the next line of stdin?

How can I fix this?

Answer

Simon picture Simon · Jan 13, 2014

stdin.read(1) reads one character from stdin. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read() or readline().

As an example, given rd.py:

from sys import stdin

x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)

... if I run this script as follows (I've typed in the 234):

C:\>python rd.py
234
x= 2
userinput= 34

betAmount= 34

... so the 2 is being picked up first, leaving the 34 and the trailing newline character to be picked up by the readline().

I'd suggest fixing the problem by using readline() rather than read() under most circumstances.