Question

How to read all lines from standard input in Python? How can I read the standard input line by line?

Answer

In Python, the standard input is exposed as sys.stdin.. As sys.stdin is a file, the lines can be iterated just like any other file in Python.

import sys

for line in sys.stdin:
    print(line)

It is also possible to read the lines as bytes instead of a Unicode str. To do that, you can use the .buffer property of the input stream.

import sys

for line in sys.stdin.buffer:
    print(line)