简体   繁体   中英

saving subprocess output in a variable

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM