Standard Input (stdin) in Python

In Python, reading from the standard input (stdin) is a common way to accept input directly from the command line or from piped data. This can be achieved using the sys.stdin file handle. This method is particularly useful for creating command-line programs that can interact with other programs or scripts.

Using stdin with Command-Line Programs

Command-line programs often use STDIN and STDOUT as file handles to read input and write output, respectively. This allows for the chaining of commands, where the output of one program can be used as the input for another. This is typically done using the pipe operator (|).

Example: Using cat and wc.py

Consider the following example where the cat program is used to print the contents of a file to STDOUT, and this output is then piped into a Python script wc.py via STDIN:

$ cat ../inputs/fox.txt | ./wc.py
      1       9      45 <stdin>

In this example, cat reads the contents of ../inputs/fox.txt and outputs it. The pipe operator (|) then funnels this output into wc.py, which processes the input from STDIN.

Redirecting Input with < Operator

Another way to provide input to a program is by using the < operator to redirect input from a file directly:

$ ./wc.py < ../inputs/fox.txt
      1       9      45 <stdin>

This command runs wc.py and redirects the contents of ../inputs/fox.txt to be read as STDIN by the script.

Combining Tools with Pipes

One of the powerful features of using STDIN is the ability to combine multiple command-line tools to perform complex tasks. For instance, the grep command can be used to search for patterns within files.

Example: Using grep and wc.py

If you want to find all lines containing the word "scarlet" in all files within a directory and count them, you can use grep in combination with wc.py:

$ grep scarlet ../inputs/*.txt | ./wc.py
    108    1192    9201 <stdin>

In this example, grep searches for the word "scarlet" in all text files in the ../inputs/ directory. The results are then piped into wc.py, which counts the lines, words, and characters from the STDIN.

These examples demonstrate the flexibility and power of using STDIN in Python scripts to create efficient and effective command-line tools.

FAQ (Frequently asked questions)

How can you read from standard input in Python?