liveBook · Manning

Standard streams

As explained in The Quick Python Book, Fourth Edition

Standard streams are the conventional input, output, and diagnostic communication channels provided to a running program.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains stream objects, read/write methods, shell redirection, and programmatic restoration through practical examples.
Examples
Demonstrates replace.py, redirected infile and outfile, pipelines, readline(), and temporary output capture.
What it assumes
Uses Python file-object methods and the sys module while contrasting stream reads with interactive input().
What you can do after
Operate/configure Python utilities to read redirected input, emit output, capture streams, and compose commands.
How it connects
Links standard streams to input(), file objects, file redirection, pipelines, and the sys module.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.