[issue45617] sys.stdin does not iterate correctly on '\r' line separator

Kelly Brazil report at bugs.python.org
Wed Oct 27 11:19:30 EDT 2021


Kelly Brazil <kellyjonbrazil at gmail.com> added the comment:

'\r' support is implicitly documented under the sys.stdin section[0]:

"These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows..."

By following the link to the open()[1] docs, it says:

"newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated."

When inspecting a newly created sys.stdin object I see that it creates an instance of _io.TextIOWrapper and its newlines attribute is set to None:

>>> sys.stdin
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
>>> print(sys.stdin.newlines)
None

Note: an oddity here is that the attribute name is newlines instead of newline.

Interestingly, when opening STDIN directly it seems to work fine:

import sys
for line in open(0, sys.stdin.mode):
    print(repr(line))

Result:
$ echo -e 'line1\rline2\rline3' | python3 linetest.py 
'line1\n'
'line2\n'
'line3\n'

So, perhaps the sys.stdin documentation should be updated to reflect this exception or it could be considered a bug to make its behavior consistent?

[0]https://docs.python.org/3/library/sys.html#sys.stdin
[1]https://docs.python.org/3/library/functions.html#open

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45617>
_______________________________________


More information about the Python-bugs-list mailing list