How to read user input until EOF in python?

rohan picture rohan · Sep 1, 2017 · Viewed 22.9k times · Source

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.

Answer

user1785721 picture user1785721 · Sep 1, 2017

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.