How to read stdin

17 Mar 2024

To read a standard input stream (stdin), use sys.stdin.

Create file stdin.py:

import os
import sys

# Don't lock console!
os.set_blocking(0, False)
s = "".join(sys.stdin.readlines())
print(s)

Create file hello.txt:

Hello world.

Redirect file input to script:

python stdin.py < hello.txt