`sys.stdin` is Python’s standard input stream. It normally receives text typed at the terminal, but a command can redirect a file or another process into it. Treat it as a file object when a utility needs to read until the input ends rather than prompt for one response. section 11.1.4 section 13.6
Choose a reading method to match the task:
- `sys.stdin.read()` reads until end-of-file. Without redirection, a terminal session waits for an end-of-file signal such as Ctrl-D. section 11.1.4
- `sys.stdin.readline()` reads one line and retains its trailing newline; `readlines()` is also available. section 13.6
- `input()` reads a prompted line and strips its newline. Use `sys.stdin` when file-like reading is more useful than a single prompted response. section 11.1.4 section 13.6
Replace text from redirected input
Run `python replace.py zero 0 < infile > outfile`. The script reads `infile` through `sys.stdin`, replaces occurrences of `zero` with `0`, and writes to `outfile` through `sys.stdout`. The shell’s `<` supplies input; `>` redirects output. Use `>>` instead to append output. section 11.1.4
Listing 11.3 File replace.py
import sys def main(): contents = sys.stdin.read() #1 sys.stdout.write(contents.replace(sys.argv[1], sys.argv[2])) #2 if __name__ == "__main__": main()
The short script shows `sys.stdin.read()` paired with `sys.stdout.write()`; its two command-line arguments supply the old and new text. section 11.1.4
For a utility that accepts an optional filename, one path can process either source. An `argparse` positional argument with `nargs='?'`, `type=argparse.FileType('r')`, and `default=sys.stdin` supplies an opened file when named and standard input otherwise. A word counter can therefore handle both `python wc_redirect.py filename` and `python wc_redirect.py < filename` without duplicating its counting logic. In a Jupyter-style notebook, save the script as a `.py` file and run it with `python` using the `!` prefix to test redirection. section 13.10 section 13.10.2




