salvaz
salvaz

Reputation: 31

Loop on sys.stdin

I know I can't enumerate() on sys.stdin, but I have to do something like this without reading entire input in memory:

for i, line in enumerate(sys.stdin):
    line = line.split()
    if sys.stdin[i][0]=='something':
        foo(sys.stdin[i][0])
    else:
        foo(sys.stdin[i+1][0])

So, how can iterate on sys.stdin without reading everything into memory?

Upvotes: 2

Views: 3902

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49784

You can use readline(), to get a single line at a time for sys.stdin. If that is inside of a generator, a simple for loop can be constructed:

def read_stdin():
    readline = sys.stdin.readline()
    while readline:
        yield readline
        readline = sys.stdin.readline()

for line in read_stdin():
    line = line.split()
    print(line)

Upvotes: 4

Related Questions