python cat (echo) equivalent for stdin

我怕爱的太早我们不能终老 提交于 2019-12-05 19:57:09

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.

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.

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