Why does sys.stdin.read () return '' forever without requiring input?

When playing with sys.stdin.read()(Terminal, Mac OS Sierra), strange behavior is detected when 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+ zon Windows

Update: I noticed the same behavior for any line of length 5 with one new line ... shorter / longer lines or more / fewer new lines behave correctly ...

# 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 when I use it in a program. I will definitely check it in the code, but still I would like to understand how to avoid these two cases when it does not work.

+4

Source: https://habr.com/ru/post/1677303/


All Articles