lightandlight lightandlight - 1 year ago 156
Python Question

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

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:

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 Source 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

from sys import stdin

x =
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):

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download