How to read user input until EOF?


My current code reads user input until line-break.
But I am trying to change that to a format, where the user can write input until strg+d to end his input.

I currently do it like this:

input = raw_input ("Input: ")

But how can I change that to an EOF-Ready version?

Asked By: Saphire




input_str =

According to the documentation:[size])

Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached.

>>> import sys
>>> isinstance(sys.stdin, file)

BTW, dont’ use input as a variable name. It shadows builtin function input.

Answered By: falsetru

You could also do the following:

acc = []
out = ''
while True:
        acc.append(raw_input('> ')) # Or whatever prompt you prefer to use.
    except EOFError:
        out = 'n'.join(acc)
Answered By: Joel Cornett

With sys.stdin.readline() you could write like this:

import sys

while True:
    input_ = sys.stdin.readline()
    if input_ == '':
    print type(input_)

Remember, whatever your input is, it is a string.

For raw_input or input version, write like this:

while True:
        input_ = input("Enter:t")
        _input = raw_input("Enter:t")
    except EOFError:
    print type(input_)
    print type(_input)
    print input_
    print _input
Answered By: Pet B

In Python 3 you can iterate over the lines of standard input, the loop will stop when EOF is reached:

from sys import stdin

for line in stdin:
  print(line, end='')

line includes the trailing n character

Run this example online:

This might be what most people are looking for, however if you want to just read the whole input until EOF into a single variable (like OP), then you might want to look at this other answer.

Answered By: arekolek
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.