Whenever redirection or piping happening, the standard input stream will be set to that. So you can directly read from sys.stdin
, like this
import sys
for line in sys.stdin:
process_line(line)
If the buffering bites you, you can adjust/disable the input buffering, like mentioned in this answer
Reduce the buffering size:
import os
import sys
for line in os.fdopen(sys.stdin.fileno(), 'r', 100):
process_line(line)
Now it buffers only 100 bytes max.
Disable the buffering:
Quoting the official documentation,
-u
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.
Note that there is internal buffering in file.readlines()
and File Objects (for line in sys.stdin
) which is not influenced by this option. To work around this, you will want to use file.readline()
inside a while 1: loop
.