How to read user input until EOF?

Saphire picture Saphire · Jan 20, 2014 · Viewed 86.6k times · Source

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?

Answer

arekolek picture arekolek · Mar 26, 2016

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: https://ideone.com/rUXCIe