Why does sys.stdin.read() return ' ' permanently without seeking input?

Viewed 1314

While playing with sys.stdin.read() (Terminal, Mac OS Sierra), found weird behavior where it becomes unusable. What's happening?

# Python 2.7.13

import sys
sys.stdin.read()
# waits for input
# user presses ctrl-d (without any input)
# returns ''
sys.stdin.read()
# doesn't wait for input
# immediately returns ''

sys.stdin.read()
# ''
sys.stdin.read()
# ''

Note: ctrl+d = EOF on Mac, ctrl+z on Windows

Update: I've noticed the same behavior for any string of length 5 with one new line...shorter/longer strings or more/less new lines behave properly...

# Python 2.7.13

import sys
sys.stdin.read()
12345
# press ctrl-d twice (only way to make single line string work?)
'12345'
# worked properly

sys.stdin.read()
1234
# user presses return and then ctrl-d
'1234\n'
# worked properly

sys.stdin.read()
12345
# return, return, ctrl-d

'12345\n\n'
# worked properly

sys.stdin.read()
12345
# return, ctrl-d
'12345\n'
# didn't work...see next call

sys.stdin.read()
# doesn't wait for input
# immediately returns ''
''

I would like to understand what causes this behavior as I'm using it in a program. I'll be sure to check for it in the code but still would like to understand how to avoid these two instances where it doesn't work.

0 Answers
Related