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' *對象,它是一個文件對象。 –