reading from stdin, while consuming no more memory than needed

xtofl picture xtofl · Jul 16, 2010 · Viewed 9.6k times · Source

I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError).

How can I have just one line in memory at a time?

The kind of code I have:

for line in sys.stdin.readlines():
    if( filter.apply( line ) ):
        print( line )

(note: I'm on 2.6)

Answer

rkhayrov picture rkhayrov · Jul 16, 2010
for line in sys.stdin:
    ...

Or call .readline() in a loop.