python cat (echo) equivalent for stdin

百般思念 提交于 2019-12-22 09:28:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!