Search code examples
pythonpython-3.xsys

When does sys.stdin await input?


What are the rules that determine whether sys.stdin awaits user input or not? For example:

>>> sys.stdin
# <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
>>> "".join(sys.stdin)
# <awaiting input...>

The second line awaits input even though I'm not "calling" sys.stdin or anything, so how does python know and what are the rules for when it waits?

Finally, is it possible to enter in sys.stdin without a trailing \n ? For example:

>>> "".join(sys.stdin)
hello
'hello\n'

To exit I have to do Returnctrl-d. Can I get the input without the \n or so I just need to always do a rstrip() at the end or something similar?


Solution

  • The second use case is using the fact that file objects are iterators; it's implicitly calling sys.stdin's __next__ method over and over until it raises StopIteration. Since it runs to completion, not just a single line, it won't return until sys.stdin is closed (typically by the other side). So the answer is what you thought, you just didn't realize that invoking the iterator protocol counts as a form of "calling".

    If you just want a single line of input, without the newline at the end, just use the input function (that implicitly pulls the result from sys.stdin, but only a single line, it doesn't wait until it's closed). Otherwise, you're stuck stripping the newlines manually.