synapse
synapse

Reputation: 5728

Filtering output of tail in with Python

A simple filtering script that looks pretty much like

import sys

for line in sys.stdin:
  print line

doesn't print anything if output of tail -f piped through it but works fine with output of cat. grep however has no problems with tail -f so I guess I should somehow change the way the script handles input.

Upvotes: 1

Views: 466

Answers (1)

falsetru
falsetru

Reputation: 369484

According to python(1) manpage:

Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line insys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

Try following instead:

import sys

while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line)
    sys.stdout.flush()

Upvotes: 3

Related Questions