问题
I thought this program will echo my console input line by line:
import os, sys
for line in sys.stdin:
print line
Unfortunately it waits for EOF (Ctrl + D) and then it produces output. How should I modify my program to get output line by line?
回答1:
Python 2.x:
for line in iter(sys.stdin.readline, ''):
print line,
Python 3.x:
for line in iter(sys.stdin.readline, ''):
print(line, end='')
See the documentation on iter() with two arguments, it actually has reading from a file like this as one of the examples.
回答2:
Python 2.x:
while True:
sys.stdout.write(sys.stdin.readline())
Python 3.x:
while True:
print(sys.stdin.readline(), end = "")
When you use the for line in file: syntax, Python manages buffering for you, meaning you have no control over how many lines will be read before your loop begins to be executed. When you call file.readline(), it will read a single line from the file and execute your loop one time.
来源:https://stackoverflow.com/questions/10971404/python-cat-echo-equivalent-for-stdin