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?

2
  • related Python 2 bug "for line in file" doesn't work for pipes Commented Oct 25, 2015 at 12:08
  • unrelated: you want print(line, end='') on Python 3 here (line includes the trailing newline unless it is EOF) Commented Oct 25, 2015 at 12:15

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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? :)

2 Comments

That is messed up. You need to just iterate over readline. See Pedraic's answer.
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.