Python Language Basic Input and Output Read from stdin


Python programs can read from unix pipelines. Here is a simple example how to read from stdin:

import sys

for line in sys.stdin:

Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended.

You can now pipe the output of another program into your python program as follows:

$ cat myfile | python

In this example cat myfile can be any unix command that outputs to stdout.

Alternatively, using the fileinput module can come in handy:

import fileinput
for line in fileinput.input():