Line Filters in Python

Here’s the translation of the Go line filter program to Python, along with explanations in Markdown format suitable for Hugo:

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in Python that writes a capitalized version of all input text. You can use this pattern to write your own Python line filters.

import sys

def main():
    # sys.stdin provides a file object connected to standard input
    # Using it with a for loop automatically reads line by line
    for line in sys.stdin:
        # Strip any trailing newline and convert to uppercase
        ucl = line.strip().upper()
        # Write out the uppercased line
        print(ucl)

if __name__ == "__main__":
    main()

In this Python version:

  1. We use sys.stdin to read from standard input. When used in a for loop, it automatically reads line by line.

  2. The strip() method removes any trailing newline characters, and upper() converts the line to uppercase.

  3. We use print() to write the uppercased line to standard output.

  4. Python’s file objects automatically handle buffering, so we don’t need to create a separate buffered reader like in the Go version.

  5. Python doesn’t have an explicit error checking mechanism for I/O operations like Go’s scanner.Err(). Instead, it uses exceptions, which we’re not explicitly handling in this simple example.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | python line_filters.py
HELLO
FILTER

This Python script achieves the same functionality as the original Go program, reading lines from standard input, converting them to uppercase, and printing them to standard output.