为什么 stdin 是逐行读取而不是像字符串那样逐字读取?
Why does stdin read line by line rather than word by word like a string?
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:
This is a test
with multiple lines
just the same as the second example
but with more words
为什么program1和program2都是单独一行输出字符串中的每个字符,而如果我们运行cat infile.txt | python3 program3.py
,它是逐行输出文本?
因为 sys.stdin
中的数据像行数组一样存储,所以当您 运行 for x in sys.stdin
时,它是一行一行而不是字符。要做到这一点你想试试这个:
for x in sys.stdin:
for y in x:
print(y)
print("")
sys.stdin
是一个文件句柄。迭代文件句柄一次生成一行。
对 sys.stdin
的描述,来自 python docs:
File objects corresponding to the interpreter’s standard input, output and error streams.
所以sys.stdin
是一个文件对象,不是字符串。要了解 File 对象的迭代器如何工作,请再次查看 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)
因此,迭代器在每次调用时都会生成下一行输入,而不是在字符串上观察到的逐字符迭代。
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:
This is a test
with multiple lines
just the same as the second example
but with more words
为什么program1和program2都是单独一行输出字符串中的每个字符,而如果我们运行cat infile.txt | python3 program3.py
,它是逐行输出文本?
因为 sys.stdin
中的数据像行数组一样存储,所以当您 运行 for x in sys.stdin
时,它是一行一行而不是字符。要做到这一点你想试试这个:
for x in sys.stdin:
for y in x:
print(y)
print("")
sys.stdin
是一个文件句柄。迭代文件句柄一次生成一行。
对 sys.stdin
的描述,来自 python docs:
File objects corresponding to the interpreter’s standard input, output and error streams.
所以sys.stdin
是一个文件对象,不是字符串。要了解 File 对象的迭代器如何工作,请再次查看 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)
因此,迭代器在每次调用时都会生成下一行输入,而不是在字符串上观察到的逐字符迭代。