How do I write a unix filter in python?

filter, python, unix

Solution

I don't know exactly what you mean by buffered in this context, but it is pretty simple to do what you are asking...

so_gen.py (generating a constant stream that we can watch):

import time
import sys
while True:
    for char in 'abcdefx':
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.1)

so_filter.py (doing what you ask):

import sys
while True:
    char = sys.stdin.read(1)
    if not char:
        break
    if char != 'x':
        sys.stdout.write(char)
        sys.stdout.flush()

Try running `python so_gen.py | python so_filter.py` to see what it does.

Problem

I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars `x` from stdin.

Original source

Related problems