How to read user input until EOF in python?

This how you can do it :

while True:
   try :
      line = input()
      ...
   except EOFError:
      pass

You can use sys module:

import sys

complete_input = sys.stdin.read()

sys.stdin is a file like object that you can treat like a Python File object.

From the documentation:

Help on built-in function read:

read(size=-1, /) method of _io.TextIOWrapper instance Read at most n characters from stream.

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

For HackerRank and HackerEarth platform below implementation is preferred:

while True:
try :
    line = input()
    ...
except EOFError:
    break;

You can read input from console till the end of file using sys and os module in python. I have used these methods in online judges like SPOJ several times.

First method (recommened):

from sys import stdin

for line in stdin:
    if line == '': # If empty string is read then stop the loop
        break
    process(line) # perform some operation(s) on given string

Note that there will be an end-line character \n at the end of every line you read. If you want to avoid printing 2 end-line characters while printing line use print(line, end='').

Second method:

import os
# here 0 and 10**6 represents starting point and end point in bytes.
lines = os.read(0, 10**6).strip().splitlines() 
for x in lines:
    line = x.decode('utf-8') # convert bytes-like object to string
    print(line)

This method does not work on all online judges but it is the fastest way to read input from a file or console.

Third method:

while True:
    line = input()
    if line == '':
        break
    process(line)

replace input() with raw_input() if you're still using python 2.

Tags:

Python 3.X

Eof