program1.py:为什么stdin是一行一行地阅读,而不是像字符串一样一字一句地阅读?
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:
这是一个测试
个与多行
只是一样的第二个例子
但具有更多的单词
为什么程序1和程序2两个输出在一个单独的行中的字符串中的每个字符,但如果我们运行cat infile.txt | python3 program3.py
,它输出一行一行的文字?
因为'sys.stdin'不是一个字符串 - 它是构造成逐行读取的特殊类。 – furas
'sys.stdin' *不是'str' *对象,它是一个文件对象。 –