Home > Article > Backend Development > How to Get Realtime Output from Subprocess.Popen in Python?
Getting Realtime Output Using subprocess
Subprocess is a powerful module in Python used to execute other programs and interact with their input and output. However, users may encounter a scenario where they need to retrieve output from the executed program in real time, without any buffering.
Problem Description
The issue arises when using subprocess.Popen with stdout set as a pipe. The output from the wrapped program appears to be buffered, resulting in chunks of data rather than line-by-line delivery. Setting the bufsize parameter to 1 or 0 does not resolve the issue.
Solution: Iterative Reading from readline()
Despite the aforementioned subprocess behavior, the following code snippet effectively retrieves output in real time:
while True: line = p.stdout.readline() if not line: break ...
Using readline() instead of iterating over p.stdout directly bypasses the buffering issue and allows for real-time output retrieval.
The above is the detailed content of How to Get Realtime Output from Subprocess.Popen in Python?. For more information, please follow other related articles on the PHP Chinese website!