You can accomplish this using the built-in function iter()
using the two-argument call method:
import functools
for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'):
...
Documentation for this:
iter(o[, sentinel])
...
If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next()
method; if the value returned is equal to sentinel, StopIteration
will be raised, otherwise the value will be returned.
One useful application of the second form of iter()
is to read lines of a file until a certain line is reached. The following example reads a file until the readline()
method returns an empty string:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)