Denys
Denys

Reputation: 4557

Immediately output user input to console

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?

Upvotes: 2

Views: 263

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

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.

Upvotes: 3

Denys
Denys

Reputation: 4557

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

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55469

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.

Upvotes: 2

Related Questions