Home > Backend Development > Python Tutorial > How can I display live subprocess output in Python while it\'s executing?

How can I display live subprocess output in Python while it\'s executing?

Patricia Arquette
Release: 2024-10-30 05:36:27
Original
341 people have browsed it

How can I display live subprocess output in Python while it's executing?

Displaying Live Subprocess Output During Execution

When utilizing subprocess in Python scripts, it can be frustrating to wait for a process to complete before accessing its output. This becomes especially evident for lengthy processes. Therefore, it becomes necessary to find a way to continuously display the output as it's generated.

In order to achieve this, you can employ the iter function to process lines immediately upon being outputted by the command. The following code sample demonstrates a common use case:

<code class="python">from __future__ import print_function # Only Python 2.x
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

Utilizing this method, you can effectively stream the output from a process while it's running, thereby eliminating the need to wait for its completion.

The above is the detailed content of How can I display live subprocess output in Python while it\'s executing?. 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