Reading Text from Standard Input

A command can consume standard input supplied by a terminal, redirected file, or upstream program without choosing the path itself.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a reusable calculator
  2. Keep reports on the right channels
  3. Give the parser a predictable record source
  4. Test without a live terminal

Trace a reusable calculator

A tool summing one number per line can read the same stream interface from typed input and from a file supplied by the shell. Text line iteration supplies record boundaries under a line-oriented format.

Keep reports on the right channels

Write machine-readable results to ordinary output and put diagnostic text on the error stream under the CLI contract. Exit status and output gives the calling script an independent success signal.[1]

Give the parser a predictable record source

A small filter accepting standard input can read the same two records from a terminal, redirected file or pipeline. Keeping prompts out of the parser allows automation to provide the records directly. The parser should have a clear rule for blank lines and end of input. See standard output and error.

Input rows: "6\n4\n"
Parse each as integer → [6,4]
Program can emit total 10 to standard output
Extra diagnostic messages belong on the error stream

Test without a live terminal

Use an in-memory text stream with valid and malformed rows. A production run may receive bytes under an environment-specific encoding. If the protocol requires a fixed encoding, set that explicitly and keep the content parser independent from input transport.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩