Home > Backend Development > Python Tutorial > How to Print Subprocess Output in Real-Time While It\'s Running?

How to Print Subprocess Output in Real-Time While It\'s Running?

Susan Sarandon
Release: 2024-10-31 21:48:28
Original
925 people have browsed it

How to Print Subprocess Output in Real-Time While It's Running?

Constantly Print Subprocess Output As Process Is Running

Problem

For programs launched using Python's subprocess module, the program must wait until the subprocess finishes executing before its output can be accessed. This can be inconvenient for long-running processes, as it prevents the program from continuing until the subprocess completes.

Solution

To enable real-time printing of the subprocess output, iterating over the subprocess's output stream can be used. This allows the program to process lines of output as soon as they become available.

Below is an example that demonstrates this approach:

<code class="python">from __future__ import print_function  # Python 2.x compatibility

import subprocess

def execute(cmd):
    popen = subprocess.Popen(cmd, 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)

# Example
for path in execute(["locate", "a"]):
    print(path, end="")</code>
Copy after login

By utilizing this iterative approach, the program can process output from the subprocess line by line as it becomes available, enabling real-time output display while the subprocess is executing.

The above is the detailed content of How to Print Subprocess Output in Real-Time While It\'s Running?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template