Show Output of shell command in realtime

Show Output of shell command in realtime
Photo by Markus Spiske / Unsplash

Python is a very powerful language that is used for automation. And a lot of times we create CLI tools using python. Python can be used to write a wrapper that would call Unix commands and we want to also see the output of those commands.

Let us see how we can use python to get the real-time output of any command executed by python.

from subprocess import Popen, PIPE

def run_generator(command):
    process = Popen(command, stdout=PIPE, shell=True)
    while True:
        line = process.stdout.readline().rstrip()
        if not line:
            break
        yield line


if __name__ == "__main__":
    unix_command = "ping -c 5 thetldr.tech"
    for result in run_generator(unix_command):
        print(result)

In the above example, we are using built-in subprocess module to get the response. run function is acting as a generator which is returning the output after every iteration.