1

I am trying to pipe the output of utilities like iostat, mongostat, etc with the command:

$ iostat -d 1 | ./script.py

in which I am using the code:

for line in sys.stdin:
    print line

I see that it hangs and does not print each line to the console. if I run without the flag to repeat every second '-d 1' where output only happens once, the script behaves as expected.

$ iostat | ./script.py

Bob R
  • 605
  • 1
  • 13
  • 25

1 Answers1

2

The data is being buffered, you can call iter on sys.stdout.readline:

import sys
for line in iter(sys.stdin.readline,""):
    print line

Running iostat on it's own just outputs a few lines, iostat -d 1 loops continuously so the data gets buffered.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thank you Padriac, this is also be the same situation with Popen from subprocess if it helps anyone. iter(p.stdin.readline,""): – Bob R Dec 23 '15 at 19:31
  • @BobR, no worries, yes, it's a specific issue related to python2, ``for line in sys.stdin:` using python3 would work just fine – Padraic Cunningham Dec 23 '15 at 19:33