Read from stdin

suggest change

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

import sys

for line in sys.stdin:
    print(line)

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 myprogram.py

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():
    process(line)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents