How to read user input until EOF?
In Python 3 you can iterate over the lines of standard input, the loop will stop when EOF is reached:
from sys import stdinfor line in stdin: print(line, end='')
line
includes the trailing \n
character
Run this example online: https://ideone.com/rUXCIe
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.
Use file.read
:
input_str = sys.stdin.read()
According to the documentation:
file.read([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)True
BTW, dont' use input
as a variable name. It shadows builtin function input
.