Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python cat (echo) equivalent for stdin

Tags:

python

echo

stdin

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?

like image 841
mnowotka Avatar asked Aug 04 '26 21:08

mnowotka


2 Answers

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.

like image 68
Andrew Clark Avatar answered Aug 07 '26 13:08

Andrew Clark


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.

like image 29
Tim Pote Avatar answered Aug 07 '26 12:08

Tim Pote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!