Python iterate over stdin line by line using input()

You can wrap stdin to strip the newlines; if you can strip all trailing whitespace (usually okay), then it's just:

for name in map(str.rstrip, sys.stdin):
    ...

You're on Py3, so that works as is; if you're on Py2, you'll need to add an import, from future_builtins import map, so you get a lazy, generator based map (that yields the lines as they're requested, rather than slurping stdin until it ends, then returning a list of all the lines).

If you need to limit to newlines, a generator expression can do it:

for name in (line.rstrip("\r\n") for line in sys.stdin):
    ...

or with an import to allow map to push work to C layer for (slightly) faster code (a matter of 30-some nanoseconds per line faster than the genexpr, but still 40 ns per line slower than the argumentless option at the top of this answer):

from operator import methodcaller

for name in map(methodcaller('rstrip', '\r\n'), sys.stdin):
    ...

Like the first solution, on Py2, make sure to get the map from future_builtins.


I wouldn't recommend you this, but you can create a generator to be used in a for loop to iterate through input line by line:

def getlines():
    while True:
        yield input()

for name in getlines():
    print(name)
    ## Remember to break out of the loop at some point