Standard streams are the conventional channels through which a running Python program receives input, produces normal output, and reports diagnostics. Python exposes them as sys.stdin, sys.stdout, and sys.stderr; each behaves like a specialized file object. section 13.6 section 3.2.7
Use the streams for these common tasks:
- Read with sys.stdin.read(), readline(), or readlines(); unlike input(), read() continues until end-of-file. section 11.1.4
- Write with print(), sys.stdout.write(), or writelines(); diagnostics can use sys.stderr. section 13.6
- Redirect streams from the command line with <, >, >>, and | to compose small programs. section 11.1.4
- Temporarily replace sys.stdout with a file, then restore sys.__stdout__ or a saved original stream. section 13.6
Replace text through redirected streams
A script can read all of standard input and write transformed content to standard output: python replace.py zero 0 < infile > outfile. Appending uses >>, while | chains one program's output into another program's input. 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()
Inspect the compact replace.py implementation: it reads sys.stdin, replaces command-line arguments, and writes through sys.stdout. section 11.1.4
