0

I am using fping program to get network latencies of a list of hosts. Its a shell program but I want to use it in my python script and save the output in some database.

I am using subprocess.call() like this:

import subprocess
subprocess.call(["fping","-l","google.com"])

The problem with this is its an infinite loop given indicated by -l flag so it will go on printing the input to the console. But after every output, I need some sort of callback so that I can save it in db. How can I do that?

I looked for subprocess.check_output() but its not working.

colidyre
  • 4,170
  • 12
  • 37
  • 53
anekix
  • 2,393
  • 2
  • 30
  • 57

1 Answers1

1

This may help you:

def execute(cmd):
    popen = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE,
                             universal_newlines=True)
    for stdout_line in iter(popen.stdout.readline, ""):
         yield stdout_line
    popen.stdout.close()
    return_code = popen.wait()
    if return_code:
        raise subprocess.CalledProcessError(return_code, cmd)

So you can basically execute:

for line in execute("fping -l google.com"):
    print(line)

For example.

David Garaña
  • 915
  • 6
  • 8