2

The following code works great for Python 3. It immediately outputs the user input to the console

import sys
for line in sys.stdin:
    print (line)

Unfortunately, it doesn't seem to work for Python 2.7 and 2.6 (yes, i do change the print command) - it just wouldn't output my lines

Am i making some stupid mistake, or is there another way to make it work for lower versions of Python?

Denys
  • 4,287
  • 8
  • 50
  • 80
  • related Python 2 bug ["for line in file" doesn't work for pipes](http://bugs.python.org/issue3907) – jfs Oct 25 '15 at 12:08
  • unrelated: you want `print(line, end='')` on Python 3 here (`line` includes the trailing newline unless it is EOF) – jfs Oct 25 '15 at 12:15

3 Answers3

3

You can use iter and sys.stdin.readline to get the output straight away similar to the behaviour in python3:

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

The "" is a sentinel value which will break our loop when EOF is reached or you enter CTRL-D on unix or CTRL-Z on windows.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

You can make this nicer for the user on Unix-like systems by importing readline, which gives you line editing capabilities, including history. But you have to use raw_input() (or input() on Python 3), rather than sys.stdin.readline().

import readline

while True:
    try:
        print raw_input()
    except EOFError:
        break

Hit CtrlD to terminate the program cleanly via EOF.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

Ok, i found the solution here.

import sys

while 1:
    try:
        line = sys.stdin.readline()
    except KeyboardInterrupt: # Ctrl+C
        break
    if not line: # EOF
        break
    print line, # avoid adding newlines (comma: softspace hack)

A bit messed up it is, innit? :)

Community
  • 1
  • 1
Denys
  • 4,287
  • 8
  • 50
  • 80
  • That is messed up. You need to just iterate over readline. See Pedraic's answer. – Burhan Khalid Oct 25 '15 at 11:47
  • @BurhanKhalid: at the time of the posting of this answer, @ Padraic Cunningham's answer was wrong (it read until an empty line instead of EOF). Even today, the answers are not equivalent: consider what happens on `Ctrl+C` and this answer doesn't print unnecessary empty lines between each input line (`print line,` vs. `print line`) – jfs Nov 07 '15 at 19:44