How to read user input until EOF in python?

Question:

I came across this problem in UVa OJ. 272-Text Quotes

Well, the problem is quite trivial. But the thing is I am not able to read the input. The input is provided in the form of text lines and end of input is indicated by EOF.
In C/C++ this can be done by running a while loop:

while( scanf("%s",&s)!=EOF ) { //do something } 

How can this be done in python .?

I have searched the web but I did not find any satisfactory answer.

Note that the input must be read from the console and not from a file.

Asked By: rohan

||

Answers:

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.
Answered By: user1785721

If you need to read one character on the keyboard at a time, you can see an implementation of getch in Python: Python read a single character from the user

Answered By: Laurent LAPORTE

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.

Answered By: MrSeeker

This how you can do it :

while True:
   try :
      line = input()
      ...
   except EOFError:
      pass
Answered By: soufiane yes

For HackerRank and HackerEarth platform below implementation is preferred:

while True:
try :
    line = input()
    ...
except EOFError:
    break;
Answered By: khush
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.