Read from stdin
suggest changePython 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents