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>
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!