相当于stdin的python cat(echo) [英] python cat (echo) equivalent for stdin

查看:48
本文介绍了相当于stdin的python cat(echo)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为该程序将逐行回显我的控制台输入:

I thought this program will echo my console input line by line:

import os, sys

for line in sys.stdin:
    print line

不幸的是,它等待EOF( Ctrl + D ),然后产生输出。我应该如何修改程序以逐行获取输出?

Unfortunately it waits for EOF (Ctrl + D) and then it produces output. How should I modify my program to get output line by line?

推荐答案

Python 2.x:

Python 2.x:

for line in iter(sys.stdin.readline, ''):
    print line,

Python 3.x:

Python 3.x:

for line in iter(sys.stdin.readline, ''):
    print(line, end='')

请参阅 iter() 具有两个参数,实际上它是从这样的文件中读取内容作为示例之一。

See the documentation on iter() with two arguments, it actually has reading from a file like this as one of the examples.

这篇关于相当于stdin的python cat(echo)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆