Read from stdin

suggest change

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

import sys

for line in sys.stdin:
    print(line)

Be aware that sys.stdin is a stream. The for-loop terminates when the stream ends. Each line already includes its trailing newline, and print adds another.

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)  # process is whatever handles one line

Feedback about page:

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



Table Of Contents