Python subprocess reads stdout while running


The main purpose of this article is to demonstrate how to read the standard output of a subprocess executed in Python.


Python subprocess reads stdout while running

Like many other builtins, Subprocess is a builtin, preinstalled with a "normal" Python installation.

It is mainly used when running tasks, processes and programs in a new process, performing a specific set of tasks and returning results.

One of the many reasons it is widely used is that it allows external programs and executables to be executed directly from within the program as a separate process.

When a program is executed using the Subprocess library, it may be necessary to display the output of this external program in real time. This may be a requirement for a number of reasons, such as when the program may be real-time and relies on calculations after a short time.

Consider the following program:

import subprocess

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise Exception(command, exitCode, output)

if __name__ ==</

Guess you like

Origin blog.csdn.net/fengqianlang/article/details/132136455