Home > Article > Backend Development > How to Print Subprocess Output in Real-Time While It\'s Running?
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.
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>
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!