pythonterminalpipeiostat

Piping iostat -d 1 to python sys.stdin


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


Solution

  • 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.