为什么stdin逐行读取而不是逐字逐句读取?

时间:2017-12-18 03:19:08

标签: python string python-3.x iteration sys

program1.py:

a = "this is a test"
for x in a:
    print(x)

program2.py:

a = """this is a test
       with more than one line
       three, to be exact"""
for x in a:
    print(x)

program3.py:

import sys

for x in sys.stdin:
    print(x)

infile.txt:

  

这是一个测试   有多条线路   与第二个例子相同   但有更多的话

为什么program1和program2都在单独的行中输出字符串中的每个字符,但是如果我们运行cat infile.txt | python3 program3.py,它会逐行输出文本?

3 个答案:

答案 0 :(得分:2)

sys.stdin is a file handle. Iterating on a file handle produces one line at a time.

答案 1 :(得分:1)

Description of sys.stdin, from the python docs:

File objects corresponding to the interpreter’s standard input, output and error streams.

So sys.stdin is a file object, not a string. To see how the iterator for File objects work, look at, once again, the python docs:

When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing)

So, the iterator yields the next line of input at every call, instead of the character-by-character iteration observed on strings.

答案 2 :(得分:-2)

因为sys.stdin中的数据存储为行数组,因此当您运行for x in sys.stdin时,它会逐行而不是字符。要做到这一点你想要的尝试:

for x in sys.stdin:
    for y in x:
        print(y)
    print("")