liveBook · Manning

Standard input

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

sys.stdin is the Python text stream object representing a process's standard input.

Standard input, often called STDIN, is the command line’s standard place for reading input. In Python, sys.stdin is the always-available text stream object used when a program receives no file arguments. section 6.0 section 6.1.1

A program can receive standard input in two common ways:

  • Pipe another program’s standard output into it with |. section 6.0
  • Redirect a file into it with <. section 6.0
  • Use argparse with nargs='*' and default=[sys.stdin] to accept zero or more readable text files, falling back to standard input. section 6.1.1

Pipe text into a counter

$ grep scarlet ../inputs/*.txt | ./wc.py 108 1192 9201 <stdin> The same program can read a file through shell redirection: $ ./wc.py < ../inputs/fox.txt 1 9 45 <stdin> section 6.0

Figure 6.1 A string diagram showing that wc.py will read one or more file inputs or possibly STDIN and will produce a summary of the words, lines, and bytes contained in each input.

Maps the input choices—files or STDIN—to the program’s line, word, and byte summary. section 6.1.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines sys.stdin as an available readable handle and demonstrates shell piping, redirection, and argparse fallback.
Examples
Demonstrates cat and grep pipelines, shell redirection, and wc.py reports labeled <stdin>.
What it assumes
Assumes basic Python file handles and command-line arguments while teaching the STDIN fallback from zero.
What you can do after
Operate command-line programs that read files, pipes, or redirected input through a unified stream interface.
How it connects
Connects standard input with standard output, pipes, input redirection, argparse, file handles, and command-line arguments.

Also explained in

Compare how 5 books explain standard input →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.